Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what List[i]++; is supposed to do?

I need to understand algorithm called bead sort. I found a c++ implementation of the algorithm however i don't fully understand it. What confuses me the most is what happens at this line:

    List[i]++;

Help me please

Here's the full code:

#include <iostream>
#include <vector>

using std::cout;
using std::vector;

void distribute(int dist, vector<int> &List) {
    //*beads* go down into different buckets using gravity (addition).
    if (dist > List.size() )
        List.resize(dist); //resize if too big for current vector

    for (int i=0; i < dist; i++)
        List[i]++;
}

vector<int> beadSort(int *myints, int n) {
    vector<int> list, list2, fifth (myints, myints + n);

    cout << "#1 Beads falling down: ";
    for (int i=0; i < fifth.size(); i++)
        distribute (fifth[i], list);
    cout << '\n';

    cout << "\nBeads on their sides: ";
    for (int i=0; i < list.size(); i++)
        cout << " " << list[i];
    cout << '\n';

    //second part

    cout << "#2 Beads right side up: ";
    for (int i=0; i < list.size(); i++)
        distribute (list[i], list2);
    cout << '\n';

    return list2;
}

int main() {
    int myints[] = {734,3,1,24,324,324,32,432,42,3,4,1,1};
    vector<int> sorted = beadSort(myints, sizeof(myints)/sizeof(int));
    cout << "Sorted list/array: ";
    for(unsigned int i=0; i<sorted.size(); i++)
        cout << sorted[i] << ' ';
}
like image 551
John Avatar asked Dec 29 '25 03:12

John


2 Answers

It increments the value of the i th element of your list, by 1.

It is simply accessing the element in the vector<int> argument to your function (called List) at index i and incrementing its value by 1

like image 37
mathematician1975 Avatar answered Dec 31 '25 17:12

mathematician1975