a.基本思想:每一次排序后找到最大的一个数
- 对于数组中的各数据,依次比较相邻的两个元素的大小
- 如果前面的数据大于后面的数据,交换着两个数据,一轮比较可以得到最小的数据。
- 使用同样的方法对剩下的数据进行比较,最后全部排好序
- 双重循环,第一个控制的是次数,第二个控制的结果的交换
2.举例实现:
假设有n个数,对其进行冒泡排序,从小到大输出结果
package com.linchong.bubblesort;
/**
*
* @version:
* @author:linchong
* @date:2018年6月2日 下午3:09:47
* @Description:(方法功能描述)
* 演示冒泡排序
* 基本思想:每一次排序后找到最大的一个数
* 对于数组中的各数据,依次比较相邻的两个元素的大小
* 如果前面的数据大于后面的数据,交换着两个数据,一轮比较可以得到最小的数据。
* 使用同样的方法对剩下的数据进行比较,最后全部排好序
*/
public class BubbleSort {
static final int SIZE = 10;
public static void bubbleSort(int[] a){
int temp;
for(int i=1;i<a.length;i++){
for(int j=0;j<a.length-1;j++){
if(a[j]>a[j+1]){
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
System.out.println("本次排序后的结果是:");
for (int k : a) {
System.out.print(k+" ");
}
System.out.print("\n");
}
}
public static void main(String[] args) {
int[] array = new int[SIZE];
int i;
for(i=0;i<SIZE;i++){
array[i] = (int)(100+Math.random()*(100+1));
}
System.out.println("排序前的数组为:");
for (int j : array) {
System.out.print(j+" ");
}
System.out.printf("\n");
bubbleSort(array);
System.out.println("排序后的数组为:");
for (int k : array) {
System.out.print(k+" ");
}
}
}