//冒泡排序:
- 参与比较的数据:23,78,12,56,11,73,90(7个数字)
- 第一次循环(6次):(把最大的数字移到最右端)
- 23,78,12,56,11,73,90 //23与78需要比较一次大小,不需要交换
– 23,12,78,56,11,73,90 //78与12 比较后交换位置
– 23,12,56,78,11,73,90 //78与56 比较后交换位置
– 23,12,56,11,78,73,90 //78与11 比较后交换位置
– 23,12,56,11,73,78,90 //78与73 比较后交换位置
– 23,12,56,11,73,78,90 //78与90需要比较一次大小,不需要交换
* 最大数在最右为90
- 参与比较的数据:23,78,12,56,11,73(6个数字)
- 第二次循环(5次):
–12,23,56,11,73,78 //同上理, 23和12比较,交换
–12,23,56,11,73,78 //23和56比较,不交换
–12,23,11,56,73,78 //56和11比较,交换
–12,23,11,56,73,78 //56和73比较,不交换
–12,23,11,56,73,78 //73和78比较,不交换
* 最大数在最右为78
- 参与比较的数据:12,23,11,56,73(5个数字)
- 第三次循环(4次):
–12,23,11,56,73 //12和23比较,不交换
–12,11,23,56,73 //23和11比较,交换
–12,11,23,56,73 //23和56比较,不交换
–12,11,23,56,73 //56和73比较,不交换
* 最大数在最右为73
- 参与比较的数据:12,11,23,56(4个数字)
- 第四次循环(3次):
– 11,12,23,56 //12和11比较,交换
– 11,12,23,56 //12和23比较,不交换
– 11,12,23,56 //23和56比较,不交换
*最大数在最右为56
- 参与比较的数据:11,12,23(3个数字)
- 第五次循环(2次):
– 11,12,23 //11和12比较,不交换
– 11,12,23 //12和23比较,不交换
* 最大数在最右为23
- 参与比较的数据:11,12(2个数字)
- 第六次循环(1次):
–11,12 //11和12比较,不交换
* 最大数在最右为12
//冒泡排序
public class RubbleSort {
public static void main(String[] args){
int arr[]={23,78,12,56,11,73,90};
int count1=0;
int count2=0;
for (int i=arr.length-1;i>0;i--){
count1++;
for (int j=0;j<i;j++){
count++;
//不管是否需要交换位置,都需要交换一次
if (arr[j]>arr[j+1]){
//交换位置
int temp;
temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
for (int i=0;i<arr.length;i++){
System.out.println(arr[i]);
}
System.out.println("总共循环了"+count1+"次");
System.out.println("总共比较了"+count2+"次");
}
}
运行结果: