1

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.

3
  • 1
    The for loops you have created are not exact replacements of the while loops in python code. Commented Jul 11, 2020 at 8:13
  • I tried using while loops, but nothing was printed to the console even after waiting a couple minutes, so I was forced to use for loops Commented Jul 11, 2020 at 8:19
  • @MichaelChourdakis Yes, I did try changing them a bit, but they still didn't work. Unless the syntax is wrong I have no idea what is going on Commented Jul 11, 2020 at 8:20

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.