package sort;
//归并排序
public class MergeSortTest {
public static void main(String[] args){
int[] data = new int[]{5, 3, 6, 2, 1, 9, 4, 8, 7};
mergeSort(data);
System.out.println("排序后的数组:");
print(data);
}
public static void mergeSort(int[] data){
sort(data, 0, data.length-1);
}
public static void sort(int[] data, int left, int right){
if (left >= right)
return;
int center = (left + right) / 2;
sort(data, left, center);
sort(data, center+1, right);
merge(data, left, center, right);
print(data);
}
public static void merge(int[] data, int left, int center, int right){
//临时数组
int[] tempArr = new int[data.length];
//右边数组的第一个元素索引
int mid = center + 1;
//tempIndex记录临时数组的索引
int tempIndex = left;
//缓存左数组的第一个元素的索引
int tmp = left;
while(left <= center && mid <=right){
if (data[left] <= data[mid]){
tempArr[tempIndex++] = data[left++];
}else{
tempArr[tempIndex++] = data[mid++];
}
}
//剩余部分依次放入临时数组(实际上两个while只会执行其中一个)
while (mid <= right){
tempArr[tempIndex++] = data[mid++];
}
while (left <= center){
tempArr[tempIndex++] = data[left++];
}
//将临时数组中的内容拷贝回原数组中
while (tmp <= right){
data[tmp] = tempArr[tmp++];
}
}
public static void print(int[] data){
for(int i=0; i<data.length; i++){
System.out.print(data[i]+" ");
}
System.out.println();
}
}
链接:http://blog.csdn.net/apei830/article/details/6591632