排序算法 快速排序源码
package algorithm;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.Random;
public class QuickSort {
public static void quickSort(int[] pData,int left,int right){
int pivotpos;
if(left < right){
pivotpos = partion(pData,left,right);
quickSort(pData, left, pivotpos);
quickSort(pData, pivotpos+1, right);
}
}
public static int partion(int[] pData,int low,int high){
int middle = pData[low];
while(low < high){
while(low < high && pData[high] >= middle){
high -- ;
}
if(low < high ){
pData[low++] = pData[high];
}
while(low < high && pData[low] <= middle){
low++;
}
if(low < high){
pData[high--] = pData[low];
}
pData[low] = middle;
}
return low;
}
public static void main(String[] args) {
/**
* 第一种测试方法
*/
// int[] pData = new int[]{49,38,65,97,76,13,27} ;
// quickSort(pData, 0, pData.length-1);
// System.out.println(Arrays.toString(pData));
/**
* 第二种测试方法
*/
// int[] pData = new int[1000000];
// Random random = new SecureRandom();
// for(int i=0;i<pData.length;i++){
// pData[i] = random.nextInt(1000000000);
// }
//// System.out.println(Arrays.toString(pData));
//
// long time = System.currentTimeMillis();
// //System.out.println(System.currentTimeMillis()+" "+Runtime.getRuntime().freeMemory());
// quickSort(pData, 0, pData.length-1);
// //System.out.println(System.currentTimeMillis()+" "+Runtime.getRuntime().freeMemory());
// System.out.println(System.currentTimeMillis()-time);
// System.out.println(Arrays.toString(pData));
/**
* 第三种测试方法
*/
// for(int i=0;i<10000;i++){
// int[] pData = new int[]{3,2,1,4,5,6,7};
// quickSort(pData, 0, pData.length-1);
// System.out.println(Arrays.toString(pData));
// }
int[] datas = new int[]{3,2,1,4,5,6,7};
long time = System.currentTimeMillis();
for(int i=0;i<10000000;i++)
{
quickSort(datas, 0, datas.length-1);
}
System.out.println(System.currentTimeMillis()-time);
for (int i = 0; i <datas.length; i++) {
System.out.println(datas[i]);
}
}
}