【发布时间】:2017-12-21 11:26:56
【问题描述】:
#include <iostream>
using namespace std;
// copy the swap function of lab10a
// copy the smallest function of lab10b
int sorting(int a[], int left, int right) {
// parameter a[] is the array to be sorted
// parameter left is the left index
// parameter right is the right index
// the function returns the index i, where a[i] is the
// smallest value in a[left..right]
// if (left > right || left < 0 || right < 0)
//error cases and return 1 for failure
// use a loop to iterate each index from left to right
// and let i be the variable in the iteration
// interchange the values of a[i] and a[ smallest(a, i, right) ]
if (left > right || left < 0 || right < 0) {
cout << "Error index out of bounds" << endl;
return -1;
}
int temp;
int index = left;
for (int i = index; i <= right; i++) {
int j = i;
while (j <= right) {
if (a[j] < a[index])
index = j;
j++;
}
temp = a[index];
a[index] = a[i];
a[i] = temp;
}
return 0; //for success
}
// Program to test sorting function
//-----------------------------------------
int main()
{
int a[] = {9,1,5,7,4,2,6,0,8,3};
// test case one
sorting(a, 1, 5);
cout << " The value in A[1..5] is sorted nondecreasingly\n";
for (int i = 0; i<10; i++)
cout << "a[" << i << "] = " << a[i] << endl;
// test case two
sorting(a, 0, 9);
cout << " The value in A[0..9] is sorted nondecreasingly\n";
for (int i = 0; i<10; i++)
cout << "a[" << i << "] = " << a[i] << endl;
return 0;
}
我在使用这种排序算法时遇到了问题。当我运行它时,它的工作似乎很奇怪,我似乎无法确定问题出在哪里。我知道问题所在的部分从第一个 for 循环的排序函数开始。棘手的部分是该函数要求数组上的边界来进行选择排序,因此由于我不是经验丰富的程序员,因此很难掌握。
【问题讨论】:
-
在调试器中逐步完成排序循环。您应该能够发现问题。