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
| package com.zyg.sort;
public class MergeSortAlgorithm { public static void mergeSort(int a[], int left, int right) { if (left < right) { int mid = (left + right) / 2; <!--more--> mergeSort(a, left, mid); mergeSort(a, mid + 1, right); merge(a, left, mid, right); } } public static void merge(int a[], int left, int mid, int right) { int len = a.length; int temp[] = new int[len]; int index = left, i = left, j = mid + 1; for (int k = 0; k < len; k++) { temp[k] = a[k]; } while (i <= mid && j <= right) { if (temp[i] < temp[j]) a[index++] = temp[i++]; else a[index++] = temp[j++]; } if (i <= mid) a[index++] = temp[i++]; if (j <= right) a[index++] = temp[j++]; } public static void printArray(int a[]) { for (int i = 0; i < a.length; i++) { System.out.println(a[i]); } } public static void main(String[] args) { int a[] = { 4, 3, 6, 7, 33, 15, 90, 65 }; mergeSort(a, 0, a.length - 1); printArray(a); } }
|