我正在创建一个小程序,它应该按升序对数组中的整数进行排序,但我非常坚持我应该使用的算法。我不能遍历数组,我必须改用递归函数。我被允许有一个可以找到数组中最小索引的辅助函数,我已经成功地完成了,但是我最难弄清楚如何使用该函数在递归函数中对我的数组进行排序。这是我目前的代码,我知道我的 sortIntegers 函数有问题。
int main()
{
int numbers[] = {8, 2, 5, 1, 3};
sortingIntegers(numbers, 5);
return 0;
}
void sortingIntegers(int *list, int size) {
if (size == 1) {
for (int i = 0; i < size; i++) {
cout << list[i] << ", ";
}
} else {
for (int z = 0; z < size; z++) {
if (list[size - 1] == smallestIndex(list)) {
for (int y = 0; y < size; y++) {
swap(list[z], list[y]);
}
}
}
sortingIntegers(list, size - 1);
}
}
int smallestIndex(int *array) {
int smallest = array[0];
for (int i = 1; i < sizeof(array); i++) {
if (array[i] < smallest) {
smallest = array[i];
}
}
return smallest;
}
最佳答案
int main()
{
int numbers[] = {8, 2, 5, 1, 0};
sortingIntegers(numbers, 0, 5);
for (int i=0;i<5;i++)
cout << numbers[i] << ' ';
return 0;
}
void sortingIntegers(int *list, int left, int size) {
if (left == size)
return;
int smallest = smallestIndex(list, left, size);
int c = list[smallest];
list[smallest] = list[left];
list[left] = c;
sortingIntegers(list, left+1 ,size);
}
int smallestIndex(int *array, int left, int size) {
int smallest = array[left];
int smIndex = left;
for (int i = left+1; i < size; i++) {
if (array[i] < smallest) {
smallest = array[i];
smIndex = i;
}
}
return smIndex;
}
这是我基于您的解决方案。首先,sizeof(array)
返回指针的大小。其次,我返回最小项的索引,而不是它的值,然后我将它与列表中的第一个元素交换。然后我调用以另一个元素(left
参数)开始的列表排序,因为我知道直到 left-1
的列表已经排序。
关于C++ 排序数组递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28426147/