简体   繁体   中英

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

Why is 89 at the end? What did I do wrong?

Change this part:

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

to

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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