【发布时间】:2017-01-27 10:33:16
【问题描述】:
应该按升序排列数组成员。谁能解释一下冒泡排序的分步过程。
//bubble sorting technique to sort the integer in ascending order
int n = 5;
int limit = n- 1;//elements from 0 to n-1
boolean flag = false;//if it is true,swapping is done
int temp;// temporary variable
for(int i=0 ; i<limit; i++){
for(int j = 0;j<limit-i;j++){
//if first element is bigger than second one , then swap
if(arr[j] > arr[j+1])
{
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;//true->swapping done
flag = true;
}
if(flag==false) break;//no swapping,so come out
else flag = false;//assign initial value
}
//display sorted array
system.out.println("the sorted array is")
for(int i=0;i<5;i++)
system.out.println(arr[i]);
}
输入:50 23 11 99 23
输出:11 23 23 50 99
【问题讨论】:
-
不要垃圾标签。而bubblesort 在保守的50 万个网站like this one 上无限地解释。
-
我认为您的代码有效 {50,23,11,99,23} -> {23,11,50,99,23} -> {11,23,50,99,23} -> {11,23, 50, 99, 23} -> {11, 23, 50, 99, 23}。错了吗?
-
是的,错了@square1001 我的结果是 11 23 23 50 99
标签: java bubble-sort