基础的排序的算法:
插入排序, 归并算法
插入排序:
package alg; import java.util.Arrays; /** * @author zha 插入排序,基础的算法 算法复杂度为O(n2) */ public class InsertSort { public static void main(String[] args) { int[] array = { 5, 2, 4, 6, 1, 3, 23, 434, 55, 6, 788, 89, 0 }; insertSort(array, 0, array.length); System.out.println(Arrays.toString(array)); } public static <T extends Comparable<T>> T[] insertSort(T[] array, int begine, int length) { // 插入排序要就插入前面的序列式有序的 for (int i = begine + 1; i < length; i++) { T key = array[i]; int j = i - 1; for (; j >= begine; j--) { if (array[j].compareTo(key) > 0){ array[j + 1] = array[j]; } else { // 得到插入点的时候直接的跳出 break; } } array[j + 1] = key; } return array; } public static int[] insertSort(int[] array, int begine, int length) { // 插入排序要就插入前面的序列式有序的 for (int i = begine + 1; i < length; i++) { int key = array[i]; int j = i - 1; for (; j >= begine; j--) { if (array[j] > key) { array[j + 1] = array[j]; } else { // 得到插入点的时候直接的跳出 break; } } array[j + 1] = key; } return array; } }
归算法:
package alg; import java.util.Arrays; /** * @author zha * 归并算法,重在思想 */ public class MergeSort { /** * @param args */ public static void main(String[] args) { int[] array = { 5, 2, 4, 6, 1, 3, 23, 434, 55, 6, 788, 89, 0 }; mergeSort(array, 0, array.length-1); System.out.println(Arrays.toString(array)); } private static void mergeSort(int[] array, int start, int end ) { if(start < end){ int mid = (start + end)>> 1; mergeSort(array, start, mid); mergeSort(array, mid+1, end); merge(array, start, mid,end); } } /** * 合并排序中合并的两端都是有序的,哨兵牌的使用 * 哨兵的作用比较的不太好 * */ private static void merge(int[] array, int start, int mid, int end) { // 创建两个变量,用来存储中间的变量 int firstl = mid - start+1; int secondl = end -mid; int[] first = new int[firstl +1]; int[] second = new int[secondl+1]; for (int i = 0; i < firstl; i++) { first[i] = array[start+i]; } for (int i = 0; i < secondl; i++) { second[i] = array[mid +i +1]; } first[firstl] = Integer.MAX_VALUE; second[secondl] = Integer.MAX_VALUE; int ii = 0 , jj =0; for (int pp = start; pp <= end; pp++) { if(first[ii] <= second[jj]){ array[pp] = first[ii]; ii++; }else{ array[pp] = second[jj]; jj++; } } } }