冒泡排序:
思想: 冒泡排序重复地走访过要排序的数列,一次比较两个元素,如果他们的顺序错误就把他们交换过来。走访数列的工作是重复地进行直到没有再需要交换,也就是说排序完成
特点:比较稳定,排序数较小是比较好
package cn.guangboyuan; /** * @author Red Ants * 微信公众号:程序员之路 * 两种冒泡排序的性能比较 */ public class DubbleSort { private static boolean checkArray(int[] data){ if(data == null || data.length == 0){ return false; } return true; } public static int[] dubbleSort(int[] data){ if(!checkArray(data)){ return null; } int temp; int runNum = 0; for (int i = 0; i < data.length; i++) { System.out.println(String.format("i=%d", i)); for (int j = i; j < data.length; j++) { System.out.print(String.format("j=%d,", j)); if(data[i] > data[j]){ temp = data[i]; data[i] =data[j]; data[j] = temp; } runNum++; } System.out.println(""); } System.out.println(String.format("dubbleSort运行次数 : %d", runNum)); return data; } public static int[] dubbleSort1(int[] data){ if(!checkArray(data)){ return null; } System.out.println(String.format("int数组长度:%d", data.length)); int temp; int runNum = 0; for (int i = 0; i < data.length-1; i++) { System.out.println(String.format("i=%d", i)); for (int j = 0; j < data.length-1-i; j++) { System.out.print(String.format("j=%d,", j)); if(data[j] > data[j+1]){ temp = data[j]; data[j] =data[j+1]; data[j+1] = temp; } runNum++; } System.out.println(""); } System.out.println(String.format("dubbleSort运行次数 : %d", runNum)); return data; } public static void main(String[] args) { int[] data = new int[]{8,4,9,13,11,99,2,1,5,3,6};; dubbleSort(data); for (int i : data) { System.out.print(i+","); } System.out.println(""); int[] data1 = new int[]{8,4,9,13,11,99,2,1,5,3,6}; dubbleSort1(data1); for (int i : data1) { System.out.print(i+","); } } }
选择排序:
思想:首先找到数组中最小的那个元素,其次,将它和第一个元素交换。接下来找第二小和第二个交换。运行时间和输入无关,数据移动最少
特点:数据移动最少,不稳定,适合排序数较少时使用
package cn.guangboyuan; import java.util.Arrays; /** * @author Red Ants * 微信公众号:程序员之路 * 选择排序 */ public class SelectionSort { public static int[] selectionSort(int[] ints){ int temp; int runNum = 0; for (int i = 0; i < ints.length; i++) { for (int j = i+1; j < ints.length; j++) { if(ints[j]<ints[i]){ temp = ints[i]; ints[i] = ints[j]; ints[j] = temp; } runNum++; } } System.out.println(String.format("运行次数:%d", runNum)); return ints; } public static void main(String[] args) { int[] ints = new int[]{8,4,9,13,11,99,2,1,5,3,6}; selectionSort(ints); System.out.println(Arrays.toString(ints)); } }
插入排序:
思想:首先数组前两个数比较排序,然后第三个数和前两个数进行排序以此类推
特点:稳定,适合大部分已排序时较好
package cn.guangboyuan; import java.util.Arrays; /** * @author Red Ants * 微信公众号:程序员之路 * 插入排序 */ public class InsertionSort { public static int[] insertionSort(int[] ints) { int target = 0; int runNum = 0; for (int i = 1; i < ints.length; i++) { int j = i; target = ints[i]; while (j > 0 && target < ints[j-1]) { ints[j] = ints[j-1]; j--; runNum++; } ints[j] = target; } System.out.println(String.format("运行次数:%d", runNum)); return ints; } public static void main(String[] args) { int[] ints = new int[]{8,4,9,13,11,99,2,1,5,3,6}; System.out.println(Arrays.toString(insertionSort(ints))); } }