描述
给一组整数,按照升序排序。使用归并排序,快速排序,堆排序或者任何其他 O(n log n) 的排序算法。
样例
给出 [3, 2, 1, 4, 5], 排序后的结果为 [1, 2, 3, 4, 5]。
代码
快排
public class Solution {
/**
* @param A: an integer array
* @return: nothing
*/
public void sortIntegers2(int[] A) {
// write your code here
if(A==null||A.length==0){
return;
}
sort(A,0,A.length-1);
}
private void sort(int[] A,int start,int end){
if(start<end){
int pivot=A[start];
int i=start,j=end;
while(i<j){
while(A[j]>=pivot&&i<j){
j--;
}
if(A[j]<=pivot){
int temp=A[i];
A[i]=A[j];
A[j]=temp;
}
while(A[i]<=pivot&&i<j){
i++;
}
if(A[i]>=pivot){
int temp=A[i];
A[i]=A[j];
A[j]=temp;
}
}
sort(A,start,i-1);
sort(A,j+1,end);
}
}
}