[英]Bubble Sort Java
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;
I am trying to get a set of numbers in an array to show up decending. 我正在尝试获取数组中的一组数字以显示降序。 However this is how the output looks. 但是,这就是输出的样子。
After descending sort: 降序后:
79 54 20 15 9 7 6 5 1 89 79 54 20 15 9 7 6 5 1 89
Why is 89 at the end? 为什么最后是89 ? What did I do wrong? 我做错了什么?
Change this part: 更改此部分:
for(int j = 1; j < last; j++)
to 至
for(int j = 1; j <= last; j++)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.