vector sorting algorithm C++

Viewed 27

I'm writing a function to sort a vector (I know there's the sort() method but I'm trying to sort the vector with an algorithm instead). Below is the function and then how I called it. It seems that temp variable isn't being used but I'm not sure why, is there something wrong with how I swapped the variables?

void vectorSort(vector <int>& numList) {
    int i;
    int j;
    int smallest;
    int temp;
    for (i = 0; i < numList.size() - 1; ++i){
        smallest = i;
        for (j = i + 1; j < numList.size(); ++j) {
            if( numList.at(j) < smallest) {
                smallest = j;
            }
        }

        temp = numList.at(i);
        numList.at(i) = smallest;
        smallest = temp;
    }
}

int main () {
vector <int> numList;
int num;

//Ask for numbers until -1 is entered
cout << "Your number is: ";
cin >> num;
while (num != -1) {
    numList.push_back(num);
    cout << "Your number is: ";
    cin >> num;
}    
// Numbers listed in order
cout << "The numbers are: ";
for (int i = 0; i < numList.size(); ++i) {
    cout << numList.at(i) << " ";
}
cout << endl;

// Calling function to sort the numList vector
vectorSort(numList);

    for (int i = 0; i < numList.size(); ++i) {
        cout << numList.at(i) << " ";
    }
    cout << endl;

return 0;
}
0 Answers
Related