使用递归实现快速排序(Java实现)
一、
1.先确定一个key值(也就是参考值),初状态定义如下
2.实现key的左边都是小于key的值,右边都是大于key的值
int key = arr[start];//防止访问溢出
while(start < end){
for(; end > start; end--){
if(arr[end] < key){
arr[start] = arr[end];
start++;
break;
}
}
for(; start < end; start++){
if(arr[start] > key){
arr[end] = arr[start];
end--;
break;
}
}
arr[start] = key;
}
3.用递归实现左右排序
QuickSort(arr,copyStart,start);//左递归
QuickSort(arr,start+1,copyEnd);//右递归
完整程序
public class Test{
public static void main(String[] args){
int[] arr = new int[]{3,5,6,1,2,8,9,3};
for(int i = 0; i < arr.length; i++){
System.out.print(arr[i]+" ");
}
System.out.print("\n");
QuickSort(arr,0,arr.length);
for(int i = 0; i < arr.length; i++){
System.out.print(arr[i]+" ");
}
}
public static void QuickSort(int arr[],int start,int sz){
int end = sz - 1;
int copyEnd = sz;
int copyStart = start;
if(end > start){
int key = arr[start];//防止访问溢出
while(start < end){
for(; end > start; end--){
if(arr[end] < key){
arr[start] = arr[end];
start++;
break;
}
}
for(; start < end; start++){
if(arr[start] > key){
arr[end] = arr[start];
end--;
break;
}
}
arr[start] = key;
}
QuickSort(arr,copyStart,start);//左递归
QuickSort(arr,start+1,copyEnd);//右递归
}
}
}
二、
public class Test {
private static int Partition(int[] arr, int start, int end) {
int key = arr[start];
while (start < end) {
while (arr[end] >= key && end > start)
end--;
arr[start] = arr[end];
while (arr[start] <= key && end > start)
start++;
arr[end] = arr[start];
}
arr[start] = key;
return start;
}
public static void quickSort(int[] arr, int start, int end) {
if (start < end) {
int index = Partition(arr, start, end);
quickSort(arr, start, index - 1);
quickSort(arr, index + 1, end);
}
}
public static void main(String[] args) {
int[] data = new int[]{1,3,2,9,7,4,6,8,20,17,25,21};
quickSort(data,0,data.length-1);
for (int temp : data) {
System.out.print(temp+"、");
}
}
}