package org.SORT;
public class mergeSort {
public static void main(String[] args) {
int a[] = {2,4,1,6,78,43,11,57,-2,33,21,58,99,123,53,643,77,40,333,78,8,17};
int t[] = new int[22];
for(int i=0; i<a.length; i++ )
System.out.print(" "+a[i]);
mergeSort(a, t, 0, a.length-1 );
System.out.println("\n"+"****************");
for(int i=0; i<a.length; i++ )
System.out.print(" "+a[i]);
}
public static void mergeSort(int[] a, int[] t, int left, int right) {
if(left < right ){
int center = (left+right) / 2;
mergeSort(a, t, left, center);
mergeSort(a, t, center+1, right);
merge(a, t, left, center+1, right);
}
}
public static void merge(int[] a, int[] t, int leftPos, int rightPos, int rightEnd) {
int leftEnd = rightPos - 1;
int tmpPos = leftPos;
int numElements = rightEnd - leftPos +1;
while(leftPos <= leftEnd && rightPos <= rightEnd)
if(a[leftPos] > a[rightPos])
t[tmpPos++] = a[rightPos++];
else
t[tmpPos++] = a[leftPos++];
while(leftPos <= leftEnd )
t[tmpPos++] = a[leftPos++];
while(rightPos <= rightEnd)
t[tmpPos++] = a[rightPos++];
for(int i=0; i<numElements; i++, rightEnd--)
a[rightEnd] = t[rightEnd];
}
}
排序算法之归并排序
最新推荐文章于 2024-07-08 22:12:26 发布