简体   繁体   中英

C++ Selection Sort (vectors)

int temp;
for (int j = 0; j < vecsize - 1; ++j) {

    int min = sort.at(j);
    for (int i = j+1; i < vecsize; ++i) {
        if (min > sort.at(i)) {
            min = sort.at(i);  
            temp = i;
        }

    }  
swap(sort.at(j), sort.at(temp));
}

I am trying to sort (in ascending order) the vector of: 23 42 4 16 8 15

However, my attempt at using selection sort outputs: 4 8 15 23 16 42

What am I doing wrong?

When you define min, you seem to be assigning it the value of the array sort at jth index. Yet, you are using an extra variable tmp to swap the elements, and you seem to fail to initialize it before the inner for loop, similar to how you initialize min. And if all the other elements in the array are smaller than the element at sort[j], tmp will be uninitialized for that iteration of the outer loop, possibly causing it to have an incorrect value in it.

int temp;
for (int j = 0; j < vecsize - 1; ++j) {
    int min = sort.at(j);
    temp = j;                                     # HERE'S WHAT'S NEW
    for (int i = j+1; i < vecsize; ++i) {
        if (min > sort.at(i)) {
            min = sort.at(i);  
            temp = i;
        }
    }  
    swap(sort.at(j), sort.at(temp));
}

You may see this code at work here . It seems to produce the desired output.

Try this : corrected-code

#include <iostream>
#include <vector>
using namespace std;

void print (vector<int> & vec) {
    for (int i =0 ; i < vec.size(); ++i) {
        cout << vec[i] << " ";
    }
    cout << endl;
}

int main() {
int temp;
vector<int> sort;

sort.push_back(23);
sort.push_back(42);
sort.push_back( 4);
sort.push_back( 16);
sort.push_back( 8);
sort.push_back(15);
print(sort);

int vecsize = sort.size();
for (int j = 0; j < vecsize - 1; ++j) {

    int min = j;
    for (int i = j+1; i < vecsize; ++i) {
        if (sort.at(min) > sort.at(i)) {
            min = i;
        }

    }  
    if (min != j)
        swap(sort.at(j), sort.at(min));
}

print(sort);
return 0;
}

If you can use C++11, you can also solve sorting (as in your example) with lambdas. It's a more powerful and optimized way. You should try it maybe in the future.

[EDITED]:

A short example:

// Example program
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

int main()
{
    std::vector<int> myVector;

    myVector.emplace_back(23);
    myVector.emplace_back(42);
    myVector.emplace_back(4);
    myVector.emplace_back(16);
    myVector.emplace_back(8);
    myVector.emplace_back(15);

    std::sort(myVector.begin(), myVector.end(),
       [](int a, int b) -> bool
    {
       return a < b;
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM