我有这个函数,该函数应该使用插入排序交织为外壳排序准备一个数组。我正在测试insertionSortInterleaved()
函数,如下所述:
void insertionSortInterleaved(int numbers[], int numbersSize, int startIndex, int gap) {
int i = 0;
int j = 0;
int temp = 0;
for (i = i + gap; i < numbersSize; i += gap) {
j = i;
while (j - gap >= startIndex && numbers[j] < numbers[j - gap]) {
temp = numbers[j];
numbers[j] = numbers[j - gap];
numbers[j - gap] = temp;
j = j - gap;
}
}
}
现在,我主要制作了一个由1-20组成的数字数组,但按降序排列,然后使它打印出该数组的每个元素。然后,我将主insertSort设置为数组,并在排序后再次返回该数组。
int main() {
int numbers[] = { 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 };
for (int i = 0; i < 20; i++) {
cout << numbers[i] << " ";
}
cout << endl;
insertionSortInterleaved(numbers, 20, 1, 5); //numbers being the array, 20 being the amount of numbers being sorted, 1 being the starting index, and 5 being the gap space)
for (int j = 0; j < 20; j++) {
cout << numbers[j] << " ";
}
cout << endl;
system("pause");
return 0;
}
它可以很好地输出原始数组,但是在“排序”之后,它将以与第一次相同的顺序输出数组。
之前:20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
之后:20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
排序后,数字不应该按升序排列吗?如果是这样,我在做什么错?任何帮助表示赞赏!谢谢!
答案 0 :(得分:2)
在while (j - gap >= startIndex || numbers[j] < numbers[j - gap])
中使用||操作员。索引+间隙也可能导致超出范围的错误监视。为此,我在for循环中更改了i = 0。
void insertionSortInterleaved(int numbers[], int numbersSize, int startIndex, int gap) {
int i = 0;
int j = 0;
int temp = 0;
for (i = 0; i < numbersSize; i += gap) {
j = i;
while (j - gap >= startIndex || numbers[j] < numbers[j - gap]) { // changed Here
temp = numbers[j];
numbers[j] = numbers[j - gap];
numbers[j - gap] = temp;
j = j - gap;
}
}
}
int main() {
int numbers[] = { 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 };
for (int i = 0; i < 20; i++) {
cout << numbers[i] << " ";
}
cout << endl;
insertionSortInterleaved(numbers, 20, 1, 1); //numbers being the array, 20 being the amount of numbers being sorted, 1 being the starting index, and 1 being the gap space)
for (int j = 0; j < 20; j++) {
cout << numbers[j] << " ";
}
cout << endl;
system("pause");
return 0;
}