public int[] mergeSort(int[] array, int n){
if(n < 2){
return a;
}
int mid = n / 2;
int[] l = new int[mid];
int[] r = new int[n-mid];
for(int i = 0; i < mid; i++){
l[i] = array[i];
}
for(int i = mid; i < end; i++){
r[i-mid] = array[i];
}
mergeSort(l, mid);
mergeSort(r, n-mid);
merge(array, l, r, mid, n-mid)
}
public void merge(
int[] a, int[] l, int[] r, int left, int right) {
int i = 0, j = 0, k = 0;
while (i < left && j < right) {
if (l[i] <= r[j]) {
a[k++] = l[i++];
}
else {
a[k++] = r[j++];
}
}
while (i < left) {
a[k++] = l[i++];
}
while (j < right) {
a[k++] = r[j++];
}
}
Quick Sort
public Solution{
public int[] quickSort(int[] array){
if(array == null){
return array;
}
quickSort(array, 0, array.length - 1);
return array;
}
public void quickSort(int[] array, int left, int right){
if (left >= right) {
return;
}
int pivotIdx = partition(array, left, right);
quickSort(array, left, pivotIdx-1);
quickSort(array, pivotIdx+1, right);
}
private void partition(int[] array, int start, int end){
int pivotIdx = start + (int)(Math.random()*(end- start));
int pivot = array[pivotIdx];
swap(array, pivot, end);
int leftBound = start;
int rightBound = end - 1;
while(leftBound <= rightBount){
if(arrat[leftBound] < pivot){
leftBound++;
}else{
swap(array, leftBound, rightBound);
rightBound--;
}
}
swap(array, leftBound, end);
return leftBound;
}
}