Search code examples
c++sortingselection-sort

Why does my adapted Selection Sort algorithm not work in C++


I have code for selection sort which I wrote over a year ago in Python here, But when I tried to adapt it to C++ it just stopped working completely, and the algorithm, which is logically exactly the same, sorts the algorithm differently and prints out a mess.

void SelectionAscending2(int array[], int numItems)
{
    int count;
    int temp;
    int minimum;
    int Pass = 0;
    //while (Pass < numItems)
    for (int i = Pass; i < numItems; i++)
    {
        count = Pass + 1;
        minimum = Pass;
        //while (count <= numItems)
        for (int j = count; j <= numItems; j++)
        {
            if (array[count] < array[minimum])
            {
                minimum = count;
                count += 1;
            }
        }
        temp = array[Pass];
        array[Pass] = array[minimum];
        array[minimum] = temp;
        Pass += 1;
    }
    for (int i = 1; i < numItems; i++)
    {
        cout << array[i] << ", ";
    }
}

int main()
{
    int myArray[8] = { 4, 2, 1, 3, 6, 5, 8, 7 };

    int length = sizeof(myArray) / sizeof(myArray[0]);
    SelectionAscending2(myArray, length);
}

This code works perfectly fine in python, but in C++ it outputs this instead: 2, 3, 4, 5, 6, 0, 7, I've been struggling with this for 3 days now and nothing I've done has worked.


Solution

  • Actually you have diverted a bit from the python code.

    • In the python code you have set the length of array (numItems) to actual length - 1 but here you have put the length (numItems) same as the actual length.

    • And also while printing you are printing from i = 1. So that's why your code is not working as expected.

    So you can do these changes (one of the ways):

    1. Change j <= numItems in second for loop to j < numItems
    2. While printing the array using the last for loop, start from i = 0