package Test1_1;
/**
* 快速排序:体现的是一种分治的思想,通过基准值和指针移动,将数组划分为两块区域,比基准值小的和比基准值大的,然后继续递归划分
* @author thinkpad
*
*/
public class QuickSort {
public static void main(String[] args) {
int[] arr={12,44,34,-2,345,68};
printArray(arr);//排序前
quickSort(arr,0,arr.length-1);
printArray(arr);//排序后
}
public static void quickSort(int[] arr, int left, int right) {
if(left<right){
int i=left;
int j=right;
int key=arr[left];
while(i<j){
while(arr[j]>key){
j--;
}
swap(arr,i,j);
while(arr[i]<key){
i++;
}
swap(arr,i,j);
}
quickSort(arr,left,i-1);
quickSort(arr,i+1,right);
}
}
public static void swap(int[] arr, int i, int j) {
// TODO Auto-generated method stub
int temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
public static void printArray(int[] arr) {
// TODO Auto-generated method stub
System.out.print("[");
for(int i=0;i<arr.length;i++){
if(i!=arr.length-1)
System.out.print(arr[i]+",");
else
System.out.println(arr[i]+"]");
}
}
}
|
|