int[] nums = {1, 7, 20, 54, 79, 15, 9, 6, 5, 89};
int length = nums.length;
boolean didSwap = true;
int last = length - 1;
// continue as long as a swap happened in the last pass,
// didSwap is a sentinel
while (didSwap) {
// assume the array is sorted
didSwap = false;
// Look at all the unsorted elements per pass
for (int i = 0; i < last; ++i) {
for (int j = 1; j < last; j++) {
if (nums[j - 1] < nums[j]) {
int temp = nums[j - 1];
nums[j - 1] = nums[j];
nums[j] = temp;
}
}
}
}
return nums;
我正在尝试在数组中获取一组数字以显示降序。然而,这是输出的外观。
降级后排序:
79 54 20 15 9 7 6 5 1 89
为什么 89 结尾?我做错了什么?
答案 0 :(得分:2)
更改此部分:
for(int j = 1; j < last; j++)
到
for(int j = 1; j <= last; j++)