public class MergeSort {
public static void mergeSort(int array[], int start, int end) {
if (start >= end) {
return;
}
int mid = (end - start) / 2 + start;
mergeSort(array, start, mid);
mergeSort(array, mid + 1, end);
merge(array, start, mid, end);
}
public static void merge(int array[], int start, int mid, int end) {
int length = end - start + 1;
int temp[] = new int[length];
int left = start;
int mid1 = mid + 1;
int i = 0;
while (left <= mid && mid1 <= end) {
if (array[left] < array[mid1]) {
temp[i++] = array[left++];
} else {
temp[i++] = array[mid1++];
}
}
while (left <= mid) {
temp[i++] = array[left++];
}
while (mid1 <= end) {
temp[i++] = array[mid1++];
}
for (int n = 0; n < length; n++) {
array[n + start] = temp[n];
}
}
public static void main(String[] args) {
int a[] = { 1, 51, 23, 4, 6, 9, 9, 10, 55 };
mergeSort(a, 0, a.length - 1);
System.out.println(Arrays.toString(a));
}
}
网友评论