简体   繁体   English

无法获取我的代码来正确排序用户输入的数字数组(使用递归)

[英]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. 更改了我的函数,以反映数组AT点“第一”的值,而不是变量“第一”本身。 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 . 此外,你总是从头开始交换时,你应该开始一个过去的first

Instead of: 代替:

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

You want: 你要:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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