Search code examples
c++sortingselection-sort

Why is my selection sort returning a value that is not in the original vector?


I've been tinkering around with it for a while now and I'm so close! Now the output seems to be continuously printing a zero as the first value of the "sorted" vector. This is homework on how to create a selection sort in C++.

Example Output

Vector: 6, 2, 11, 1, 12, 4

Sorted Vector: 0, 2, 11, 6, 12, 4

Code

void selectionSort (vector<int>& data)
{
    int min, temp, n=data.size(), i, j;

    for (i=0; i<n; i++)
    {
        min = i;
        for (j=i+1; j<n; j++)
        {   
            if (data[min]>data[j])
            {
                min=j;
            }   
            temp=data[min];
            data[min]=data[i];
            data[i]=temp;
        }
        return;
    }   
}

int main()
{
    int n;
    vector<int> data;

    cout<<"Vector length?: "<<endl;
    cin>>n;

    srand(time(0));
    for (int i=0; i<n; i++)
    {
        data.push_back(rand()%20+1);
    }

    cout<<"Vector: "<<endl;
    for (int i=0; i<n; i++)
    {
        cout<<data[i]<<" "<<endl;
    }

    selectionSort(data);

    cout<<"Selection Sorted Vector: "<<endl;
    for (int i=0; i<data.size(); i++)
    {
        cout<<data[i]<<" "<<endl;
    }

    system("Pause");

    return 0;




}

Solution

  • Consider the following correct implementation of a selection sort and compare it to yours:

    #include <iostream>
    #include <vector>
    
    void selection_sort(std::vector<int> &numbers)
    {
        // Iterate through all possible start indices.
        for (int i = 0; i < numbers.size(); ++i)
        {
            // Determine the index of the minimum for this iteration.
            int index_of_min = i;
            for (int j = i; j < numbers.size(); ++j)
            {
                if (numbers[j] < numbers[index_of_min])
                {
                    index_of_min = j;
                }
            }
            // Swap the minimum element with the element at the start index.
            int temp = numbers[i];
            numbers[i] = numbers[index_of_min];
            numbers[index_of_min] = temp;
        }
    }
    
    int main()
    {
        std::vector<int> numbers = { 20, 17, 13, 12, 25 };
    
        selection_sort(numbers);
    
        for (size_t i = 0; i < numbers.size(); ++i)
        {
            std::cout << numbers[i] << " ";
        }
    }