04_排序_归并排序
【基本原理】
对于给定的一组数据(假设有n个数据),首先将每两个相邻长度为1的子序列进行归并,得到n/2个长度为2或者1的有序子序列,再将其两两合并,反复此过程,得到一个有序序列。
【代码】
package com.sort; //归并算法 public class TestMergeSort { //目的就是将一个数组分成两组,按从小到大顺序排列后重新组合成新数组,即“并” public static void mergeArray(int[] a,int first,int mid,int last,int[] temp){ int i=first,j=mid+1; int m=mid,n=last; //以mid为分界点,将a[]分为两组 : a[i...m]和a[j...n] int k=0; while(i<=m&&j<=n){ //其中一个条件不满足,可能就是一个数组的数据全部赋值到temp中,另一个还有残留数据 if(a[i]<=a[j]){ temp[k++]=a[i++]; }else{ temp[k++]=a[j++]; } } while(i<=m){ temp[k++]=a[i++]; } while(j<=n){ temp[k++]=a[j++]; } for(i=0;i<k;i++){ //将temp[]中的排序好的值 重新放回 a[] a[first+i]=temp[i]; } } //利用递归的方式拆开数据,即“归” public static void mergeSort(int a[],int first,int last,int[] temp){ if(first<last){ //这里的last是最后一个数据的位置坐标,比长度小1 int mid=(first+last)/2; //寻找中间的位置坐标值 mergeSort(a,first,mid,temp); //左边有序 mergeSort(a,mid+1,last,temp); //右边有序 mergeArray(a,first,mid,last,temp); //有序之后合并 } } public static void mergeSortFinal(int[] a){ //传入一个数据即可 int last=a.length; //这里的last是长度 int[] temp = new int[last]; mergeSort(a,0,last-1,temp); } public static void main(String[] args){ int a[]={2,9,0,8,7,1,5,4,3,6}; mergeSortFinal(a); for(int i=0;i<a.length;i++){ System.out.print(a[i]+" "); } } }