算法之二路归并排序
public class SortTest { private static int ARRAY_NUMBER=10; public static void main(String[] args) { // TODO Auto-generated method stub //准备待排序的序列 Random random = new Random(); int[] array = new int[ARRAY_NUMBER]; for(int i = 0 ; i < array.length; i++){ array[i] = random.nextInt(20); } System.out.println("数组的初始排序如下:\n"); System.out.println(Arrays.toString(array)); mergeSort(array,0,array.length-1); System.out.println("数组的归并排序后如下:\n"); System.out.println(Arrays.toString(array)); } //二路归并排序 private static void mergeSort(int[] list,int left,int right){ if(left < right){ int mid = (left+right)/2; mergeSort(list,left,mid); mergeSort(list,mid+1,right); mergeration(list,left,mid,right); } } private static void mergeration(int[] list, int left, int mid, int right) { // TODO Auto-generated method stub int i,j,k; int[] temp = new int[right-left+1]; k = 0; i=left; j=mid+1; while(i<=mid&&j<=right){ if(list[i] <= list[j]){ temp[k++] = list[i++]; }else{ temp[k++] = list[j++]; } } while(i<=mid){ temp[k++] = list[i++]; } while(j<=right){ temp[k++] = list[j++]; } //排好序后复制回原来数组的相应分段中 for(i=0;i<temp.length;i++){ list[left+i]=temp[i]; } } }