public class Solution {
/**
* @param A an integer array
* @return void
*/
public void sortIntegers(int[] A) {
// Write your code here
if (A == null || A.length == 0) {
return;
}
mergeSort(A, 0, A.length - 1);
}
private void mergeSort(int[] A, int start, int end) {
if (start >= end) {
return;
}
int mid = start + (end - start) / 2;
mergeSort(A, start, mid);
mergeSort(A, mid + 1, end);
merge(A, start, mid, end);
}
private void merge(int[] A, int start, int mid, int end) {
int[] temp = new int[end - start + 1];
int i = start;
int j = mid + 1;
int k = 0;
while (i <= mid && j <= end) {
if (A[i] <= A[j]) {
temp[k++] = A[i++];
} else {
temp[k++] = A[j++];
}
}
while (i <= mid) {
temp[k++] = A[i++];
}
while (j <= end) {
temp[k++] = A[j++];
}
k--;
while (k >= 0) {
A[end--] = temp[k--];
}
}
}
2016年9月12日星期一
Merge Sort
订阅:
博文评论 (Atom)
没有评论:
发表评论