归并排序
Java代码实现如下
public class MergeSort_correct {
// sort()功能是将前后相邻的两个有序表,归并为一个有序表的方法
public static void sort(int[] arr,int low, int middle, int high)
{
int[] tmpArr = new int[high - low + 1];//申请内存空间
int i = low;
int j = middle + 1;
int k = 0;//tmpArr的索引
while(i <= middle && j <= high)
{
if(arr[i] <= arr[j])
tmpArr[k++] = arr[i++];
else
tmpArr[k++] = arr[j++];
}
while(i <= middle)
tmpArr[k++] = arr[i++];
while(j <= high)
tmpArr[k++] = arr[j++];
//新数组中的数覆盖到 arr数组
for(int x=0; x<tmpArr.length; x++)
{
arr[x+low] = tmpArr[x];
}
}
public static void merge(int[] arr, int low, int high)
{
if(low < high) //递归跳出条件
{
int mid = (low + high)/2;
merge(arr, low, mid);
merge(arr, mid+1, high);//对右侧子序列递归排序
sort(arr, low, mid, high);
}
}
public static void main(String[] args)
{
int [] testArr = new int[]{49, 38,65,97,76,13,27,13};
merge(testArr, 0, testArr.length - 1);
for(int y:testArr)
System.out.print(y+" ");
}
}