package first;
//归并排序
public class MergeSort {
//产生随机数组的方法
public static int[] getarray() {
int[] nums = new int[10];
for (int i = 0; i < nums.length; i++) {
nums[i] = (int) (Math.random()*100);
}
return nums;
}
//归并方法
public static int[] Sort(int[] nums, int low, int high) {
int mid = (low + high) / 2;
if (low < high) {
Sort(nums, low, mid);// 左边
Sort(nums, mid + 1, high);// 右边
Merge(nums, low, mid, high);//左右归并
}
return nums;
}
//排序方法
public static void Merge(int[] nums, int low, int mid, int high) {
int[] temp = new int[high - low + 1];
int i = low;//左指针
int j = mid + 1;//右指针
int k = 0;
//通过比较把较小的数移到数组中
while (i <= mid && j <= high) {
if (nums[i] < nums[j])
temp[k++] = nums[i++];
else
temp[k++] = nums[j++];
}
//把右边剩余的数移到数组中
while(j<=high)
temp[k++] = nums[j++];
//把左边剩余的数移到数组中
while(i<=mid)
temp[k++] = nums[i++];
//把新数组中的数覆盖原数组
for(int m=0;m < temp.length;m++)
nums[m+low] = temp[m];
}
public static void main (String args[]) {
int nums[]=getarray();
System.out.println("随机数组为:");
for (int i = 0; i < nums.length; i++) {
System.out.print(nums[i]+" ");
}
Sort(nums, 0, nums.length-1);
System.out.println("排序后:");
for (int i = 0; i < nums.length; i++) {
System.out.print(nums[i]+" ");
}
}
}
java_归并排序
最新推荐文章于 2019-05-10 21:36:27 发布