算法之二路归并排序
Posted 纳木错星空
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了算法之二路归并排序相关的知识,希望对你有一定的参考价值。
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]; } } }
以上是关于算法之二路归并排序的主要内容,如果未能解决你的问题,请参考以下文章