简单的快速排序算法,我竟然花费了如此多的时间来写作,好好学习。
/**
*
*/
package basic.sort; import java.util.Arrays;
import java.util.Random; public class QuickSort { public static <AnyType extends Comparable<? super AnyType>>
void quickSort(AnyType[] arr){
if(arr == null || arr.length ==0){
return ;
}
AnyType key = arr[0];
int low = 0,high =arr.length -1;
while(low < high){
while(arr[high].compareTo(key) > 0 && high > 0){
--high ;
}
while(arr[low].compareTo(key) <= 0 && low < arr.length-1){
++low;
}
if(low < high){
AnyType tmp = arr[low];
arr[low] = arr[high];
arr[high] = tmp;
}
}
arr[0] = arr[high];
arr[high] = key; //println(Arrays.toString(arr)); quickSort(arr, 0 ,high-1);
quickSort(arr,high+1,arr.length-1);
} public static <AnyType extends Comparable<? super AnyType>>
void quickSort(AnyType[] arr, int l,int h){
if(arr == null || arr.length ==0
|| l >= h){
return ;
}
AnyType key = arr[l];
int low = l+1;
int high = h; while(low < high){
while(arr[high].compareTo(key) > 0 && high > l ){
--high ;
}
while(arr[low].compareTo(key) < 0 && low < h){
++low;
}
if(low < high){
AnyType tmp = arr[low];
arr[low] = arr[high];
arr[high] = tmp;
}
}
arr[l] = arr[high];
arr[high] = key; quickSort(arr, l ,high-1);
quickSort(arr,high+1,h);
} public static void main(String[] args) {
Random rand = new Random();
Integer[] arr = new Integer[10];
for(int i = 0 ;i <10 ;i++){
arr[i] = rand.nextInt(1000);
}
println(Arrays.toString(arr));
quickSort(arr);
println(Arrays.toString(arr));
} public static void println(String str){
System.out.println(str);
} }
认真努力