繁体   English   中英

冒泡排序Java

[英]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;

我正在尝试获取数组中的一组数字以显示降序。 但是,这就是输出的样子。

降序后:

79 54 20 15 9 7 6 5 1 89

为什么最后是89 我做错了什么?

更改此部分:

for(int j = 1; j < last; j++)

for(int j = 1; j <= last; j++)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM