簡體   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