首先是插入排序,原理没什么好说的
package com.bird.seven; /** * 插入排序的实现 * @author Bird * */ public class InsertSort { public static void insertSort(int[] a){ int j; for(int i = 1; i < a.length; i++){ int temp = a[i]; for(j = i; j > 0 && temp < a[j-1]; j--) a[j] = a[j-1]; a[j] = temp; } } public static void main(String[] args){ int[] a = {34,8,64,51,32,21}; insertSort(a); for(int t : a) System.out.print(t+" "); } }
运行结果为
8 21 32 34 51 64
然后是希尔排序
package com.bird.seven; /** * 希尔排序的实现 * @author Bird * */ public class ShellSort { public static void shellSort(int [] a){ for(int gap = a.length/2; gap > 0; gap /= 2){ for(int i = gap; i < a.length; i++){ int temp = a[i]; int j = i; for(; j >= gap&&temp < a[j-gap]; j -= gap) a[j] = a[j-gap]; a[j] = temp; } } } public static void main(String [] args){ int [] a = {81,94,11,96,12,35,178,95,28,58,41,75,15}; shellSort(a); for(int t : a) System.out.print(t + " "); } }
运行结果为
11 12 15 28 35 41 58 75 81 94 95 96 178
归并排序为
package com.bird.seven; /** * 归并排序的实现 * @author Bird * */ public class MergeSort { public static void mergeSort(int[] a, int[] temp, int left, int right){ if(left < right){ int center = (left + right)/2; mergeSort(a,temp,left,center); mergeSort(a,temp,center+1,right); merge(a,temp,left,center+1,right); } } public static void mergeSort(int [] a){ int [] temp = new int [a.length]; mergeSort(a,temp,0,a.length-1); } private static void merge(int[] a, int[] temp, int leftPos, int rightPos, int rightEnd) { int leftEnd = rightPos -1; int tmpPos = leftPos; int numElements = rightEnd - leftPos + 1; while(leftPos <= leftEnd && rightPos <= rightEnd){ if(a[leftPos] <= a[rightPos]) temp[tmpPos++] = a[leftPos++]; else temp[tmpPos++] = a[rightPos++]; while(leftPos <= leftEnd) temp[tmpPos++] = a[leftPos++]; while(rightPos <= rightEnd) temp[tmpPos++] = a[rightPos++]; for(int i = 0 ; i < numElements; i++, rightEnd--){ a[rightEnd] = temp[rightEnd]; } } } public static void main(String [] args){ int [] a = {81,94,11,96,12,35,178,95,28,58,41,75,15}; mergeSort(a); for(int t : a) System.out.print(t + " "); } }
运行结果为
11 12 15 28 35 41 58 75 81 94 95 96 178