* 快速排序
* 一、快速排序的思想
* 快速排序通过将一个数组划分成俩个子数组,然后通过递归调用自身为每一个子数组进行快速排序来实现
* 二、如何进行划分
* 设定关键字,将比关键字小的放在一组,比关键字大的放在另一组
* 三、如何自动设定关键字
* 设置数组最右端的数据为关键字
package com.algorithm;
/**
* 快速排序
* 一、快速排序的思想
* 快速排序通过将一个数组划分成俩个子数组,然后通过递归调用自身为每一个子数组进行快速排序来实现
* 二、如何进行划分
* 设定关键字,将比关键字小的放在一组,比关键字大的放在另一组
* 三、如何自动设定关键字
* 设置数组最右端的数据为关键字
* @author lenovo
*
*/
public class QuickSort {
/**
* 划分数组
*/
public static int partition(long attr[],int left,int right,long point){
int leftPtr= left-1;
int rightPrt = right +1;
while (true) {
//循环,比关键字小的留在左端
while (leftPtr < rightPrt && attr[++leftPtr]<point) ;
//将比关键字大的留在右边,
while (rightPrt > leftPtr && attr[--rightPrt]>point) ;
if(leftPtr >= rightPrt){
break;
}else{
long temp = attr[leftPtr];
attr[leftPtr] = attr[rightPrt];
attr[rightPrt] =temp;
}
}
//将关键字和当前leftPtr所指的这一个进行交换
long tmp = attr[leftPtr];
attr[leftPtr] = attr[right];
attr[right] = tmp;
return leftPtr;
}
public static void sort(long[] arr, int left, int right) {
if(right - left <= 0) {
return;
} else {
//设置关键字
long point = arr[right];
//获得切入点,同时对数组进行划分
int partition = partition(arr, left, right, point);
//对左边的子数组进行快速排序
sort(arr,left,partition - 1);
//对右边的子数组进行快速排序
sort(arr,partition + 1, right);
}
}
public static void displayArr(long attr[]){
System.out.print("[");
for(long num : attr) {
System.out.print(num + " ");
}
System.out.print("]");
System.out.println();
}
public static void main(String[] args) {
long[] attr = new long[10];
for (int i = 0; i < 10; i++) {
attr[i] = (long) (Math.random()*99);
}
displayArr(attr);
sort(attr, 0, attr.length - 1);
displayArr(attr);
}
}