归并排序(java)

来源:互联网 发布:消原唱软件 编辑:程序博客网 时间:2024/04/29 17:20

基本排序:归并(Merge)排序法是将两个(或两个以上)有序表合并成一个新的有序表,即把待排序序列分为若干个子序列,每个子序列是有序的。然后再把有序子序列合并为整体有序序列。

public class MergingSort {public int[] mergingSort(int[] data,int left,int right){if(left < right){int center = (left+right)/2;mergingSort(data,left,center);mergingSort(data,center+1,right);mergeArray(data,left,center,right);}return data; }//将数组中left--center,center+1--right的数组的值进行合并public  void mergeArray(int[] data,int left,int center,int right){//设定一个数组用于排序int[] tempArray = new int[data.length];//设定一个值来保存左节点,用于标记、新的数组int sLeft = left;int temLeft = left;int mid = center + 1;while(left<=center&&mid<=right){if(data[temLeft]<data[mid]){tempArray[sLeft++] = data[temLeft++];}else{tempArray[sLeft++] = data[mid++];}}//将剩下的右边的数据复制到数组中while(temLeft<=center){tempArray[sLeft++] = data[temLeft++]; }//将剩下的左边的数据复制到数组中while(mid<=right){tempArray[sLeft++] = data[mid++];}//将临时数组中的数据,复制回原数据while(left<=right){data[left]=tempArray[left++];}}public static void main(String args[]){int[] a = {10,9,8,7,6,5,4,3,2,1};int[] result = new MergingSort().mergingSort(a, 0, a.length-1);for(int i=0;i<result.length;i++){System.out.println(result[i]);}}}


原创粉丝点击