C++ Can';让我的代码正确排序用户输入的数字数组(使用递归)
就我个人而言,我无法正确地排序这些代码。这是一种递归实践,通过对用户输入的五个数字进行排序,然后从最小到最大显示这五个数字。它大部分操作都正确,但偶尔会弄乱第一个或最后一个数字,并将其与数组中的另一个数字切换。我知道问题在函数内部,在第二个“if”语句中,is在哪里进行交换,但我不知道如何解决它,我真的很想知道如何继续。这是我的密码:C++ Can';让我的代码正确排序用户输入的数字数组(使用递归),c++,sorting,recursion,C++,Sorting,Recursion,就我个人而言,我无法正确地排序这些代码。这是一种递归实践,通过对用户输入的五个数字进行排序,然后从最小到最大显示这五个数字。它大部分操作都正确,但偶尔会弄乱第一个或最后一个数字,并将其与数组中的另一个数字切换。我知道问题在函数内部,在第二个“if”语句中,is在哪里进行交换,但我不知道如何解决它,我真的很想知道如何继续。这是我的密码: #include <iostream> #include <array> using namespace std; void mySo
#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);
}
#包括
#包括
使用名称空间std;
void mySort(int nums[],int first,int size);
int main()
{
整数五位数[5];
int firstNum=0;
int size=5;
不能有五个数字[i];
coutEDIT:让代码正常工作,但忘记了最重要的部分,即:
如果要将索引与数组值进行比较,请使用:
if (nums[first] < nums[i])
你想要:
for (int i = first + 1; i < 5; i++)
for(int i=first+1;i<5;i++)
你需要向你的橡皮鸭解释你的算法。同样,在你的算法中,相同的值first
既用作比较“firstif (first < nums[i])
for (int i = 0; i < 5; i++)
for (int i = first + 1; i < 5; i++)