简体   繁体   中英

Can't get my code to correctly sort user input array of numbers (using recursion)

For the life of me I can't get this code to sort correctly. This is a recursion practice, by sorting five numbers that the user inputs, then I display those five numbers from least to greatest. It does most of it correctly, but occasionally it will mess the first or last number up, and switch it with another number in the array. I know the problem is inside the function where is does the swapping, in that second 'if' statement, but I can't figure out how to fix it, I would really appreciate some direction as to how to proceed. Here is my code:

#include <iostream>
#include <array>

using namespace std;

void mySort(int nums[], int first, int size);

int main()
{
    int fiveNumbers[5];
    int firstNum = 0;
    int size = 5;
    cout << "Please enter five numbers, pressing enter after each.\n\n";
    for (int i = 0; i < 5; i++)
    {
        cout << "Enter a number: ";
        cin >> fiveNumbers[i];
        cout << endl;
    }

    mySort(fiveNumbers, firstNum, size);

    for (int i = 0; i < size; i++)
    {
        cout << fiveNumbers[i] << endl;
    }

    system("PAUSE");
    return 0;
}

void mySort(int nums[], int first, int size)
{
    if (size == 0)
    {
        return;
    }
    for (int i = 0; i < 5; i++)
    {
        if (first < nums[i])
        {
            swap(nums[first], nums[i]);
        }
    }
    first++;
    size--;
    return mySort(nums, first, size);
}

Changed my function to reflect the value of the array AT point 'first', instead of the variable 'first' itself. So far it has worked every time!

void mySort(int nums[], int first, int size)
{
    if (size == 0)
    {
        return;
    }
    for (int i = 0; i < 5; i++)
    {
        if (nums[first] < nums[i])
        {
            swap(nums[first], nums[i]);
        }
    }
    first++;
    size--;
    return mySort(nums, first, size);
}

EDIT: Got your code working but forgot the most important part, namely:

You're comparing the index to the array value, use:

if (nums[first] < nums[i])

Instead of:

if (first < nums[i])

Also, you always start swapping from the beginning when you should be starting one past first .

Instead of:

for (int i = 0; i < 5; i++)

You want:

 for (int i = first + 1; i < 5; i++)

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