排序算法–冒泡排序
原理:
利用类似冒泡的原理,每次把最大(最小)的数据移动到最后,以此达到最终数据为有序的结果
实现思路:
1.外层循环控制总共需要运行多少次才能把所有数据排序
2.内存循环用于判断相邻的两个数据的大小,然后进行数据交换,把最大(最小)值移动到最后
package cn.sort;
import java.util.Arrays;
/**
* @author 作者 jinjin.peng@hand
* @version 1.0
* @date 创建时间:2017/4/13 09:49
*/
public class Test1 {
/**
* 冒泡排序:(升序排序)
* 每次运行一趟,则对相邻的两个数据做对比,把大的数据往后移动
*
* @param array
*/
public static void bubbleSort1(int[] array) {
int tmp = 0;
for (int i = 0; i < array.length - 1; i++) {
for (int j = 0; j < array.length - 1; j++) {
//如果前面的数据比后面的数据大,则进行位置交换
if (array[j] > array[j + 1]) {
tmp = array[j];
array[j] = array[j + 1];
array[j + 1] = tmp;
}
}
System.out.println("第 " + i + " 趟 " + Arrays.toString(array));
}
}
/**
* 冒泡排序:(升序排序)
* 每次运行一趟,则对相邻的两个数据做对比,把大的数据往后移动
* 优化1:减少运行次数,没运行一次,后面的数据已经排好序,无须再次比对
*
* @param array
*/
public static void bubbleSort2(int[] array) {
int tmp = 0;
for (int i = 0; i < array.length - 1; i++) {
for (int j = 0; j < array.length - 1 - i; j++) {
//如果前面的数据比后面的数据大,则进行位置交换
if (array[j] > array[j + 1]) {
tmp = array[j];
array[j] = array[j + 1];
array[j + 1] = tmp;
}
}
System.out.println("第 " + i + " 趟 " + Arrays.toString(array));
}
}
/**
* 最终版本: 由于冒泡排序每次是把当前最大的一个数据移动到最后面,因此在运行每一趟的时候 如果没有数据交换,则说明数据本身已经全部排序完成
*
* 外层循环控制趟数:每一趟可以把一个数字移动到最后
* 内存循环控制次数:每一次判断相邻的数据是否需要进行交换,以达到把当前这一趟中的 最大(小)数据,移动到最后
*
* 优化点1:减少次数: 因为每次已经把最大(小)数已经移动到最后,因此后面的 第 length-1-i次的数据是不需要处理的
* 优化点2:减少趟数: 因为每次都是相邻的两个数据比较大小,所以如果此轮中不存在数据交换的话,那后面则是已经排好序的数据,无需再次排序
*/
public static void bubbleSort(int[] array) {
int tmp = 0;
boolean sorted = true;
for (int i = 0; i < array.length - 1; i++) {
sorted = true;
for (int j = 0; j < array.length - 1 - i; j++) {
//如果前面的数据比后面的数据大,则进行位置交换
if (array[j] > array[j + 1]) {
tmp = array[j];
array[j] = array[j + 1];
array[j + 1] = tmp;
sorted = false;
}
}
if (sorted) {
break;
}
System.out.println("第 " + i + " 趟 " + Arrays.toString(array));
}
}
public static void main(String[] args) {
int[] array = {6, 2, 1, 0, 5, 4, 3, 7, 8, 9};
bubbleSort1(array);
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + "\t");
}
System.out.println();
System.out.println("==============================");
bubbleSort2(array);
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + "\t");
}
System.out.println();
System.out.println("==============================");
int[] array2 = {5, 4, 3, 2, 1, 0, 5, 6, 7, 8, 9};
bubbleSort(array2);
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + "\t");
}
}
}