排序
解法一:快排,递归实现
public class Solution {
public void qsort(int [] num, int low, int high){
int i = low, j=high;
if(low >= high) return ;
while(low < high){
//
while(low < high && num[high] >= num[i]) high--;
while(low < high && num[low] <= num[i]) low++;
int temp = num[high];
num[high] = num[low];
num[low] = temp;
}
int temp = num[low];
num[low] = num[i];
num[i] = temp;
qsort(num, i, low-1);
qsort(num, low+1, j);
}
public void sortColors(int[] A) {
qsort(A, 0, A.length-1);
}
}
解法二:归并排序,递归实现
public class Solution {
public void mergesort(int[] num, int low, int high){
if(low >= high) return;
int mid = (low + high) / 2;
mergesort(num, low, mid);
mergesort(num, mid+1, high);
//
int k,i, j, b[] = new int[mid-low+1], c[] = new int[high-mid];
for(i=0,j=low; j<=mid; j++, i++){
b[i] = num[j];
}
for(i=0, j=mid+1; j<=high; j++,i++){
c[i] = num[j];
}
i=0;
j=0;
for(k=low; i<b.length&&j<c.length; k++){
if(b[i] >= c[j]) num[k] = c[j++];
else num[k] = b[i++];
}
while(i < b.length) num[k++] = b[i++];
while(j < c.length) num[k++] = c[j++];
}
public void sortColors(int[] A) {
mergesort(A, 0, A.length-1);
}
}
解法三:堆排序
public class Solution {
public void exchange(int []a, int i, int j){
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
public void heapify(int [] a, int pos, int size){
int l = pos*2 + 1;
int r = l + 1;
int largest = pos;
if(l <= size && a[l] > a[largest])
largest = l;
if(r <= size && a[r] > a[largest])
largest = r;
if(largest != pos){
exchange(a, pos, largest);
heapify(a, largest, size);
}
}
public void buildHeap(int [] a, int size){
for(int i=(size-1)/2; i>=0; i--){
heapify(a, i, size);
}
}
public void heapSort(int [] a){
int size = a.length-1;
buildHeap(a, size);
for(int i=a.length-1; i>0; i--){
exchange(a, 0, i);
size--;
heapify(a, 0, size);
}
}
public void sortColors(int[] A) {
heapSort(A);
}
}