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]+" ");
}
}
}