1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
| package sort.merge;
import java.util.ArrayList; import java.util.Arrays; import java.util.Scanner;
public class MergeSort { public static void main(String[] args) { Integer[] arr = {6, 5, 4, 3, 2, 1}; System.out.println("排序前:" + Arrays.toString(arr)); mergeSort(arr, 0, arr.length - 1);
System.out.println("排序后:" + Arrays.toString(arr)); }
public static Integer[] scanNum() { Scanner sc = new Scanner(System.in); ArrayList<Integer> list = new ArrayList<>(); System.out.print("输入一串数字,空格分开,以#结束:"); while (!sc.hasNext("#")) { int a = sc.nextInt(); list.add(a); }
return list.toArray(new Integer[0]); }
public static void merge(Integer[] arr, int low, int mid, int high) { int[] tmp = new int[high - low + 1]; int i = 0; int j = low, k = mid + 1;
while (j <= mid && k <= high) { if (arr[j] < arr[k]) { tmp[i++] = arr[j++]; } else { tmp[i++] = arr[k++]; } }
while (j <= mid) { tmp[i++] = arr[j++]; } while (k <= high) { tmp[i++] = arr[k++]; }
for (int l = 0; l < tmp.length; l++) { arr[low + l] = tmp[l]; } }
public static void mergeSort(Integer[] arr, int low, int high) {
if (low < high) { int mid = (low + high) / 2; mergeSort(arr, low, mid); mergeSort(arr, mid + 1, high); merge(arr, low, mid, high); } }
}
|