- 快排的核心代码(递归):
private static void quickSort(int[] a, int i, int j) {if (i < j) {
int mid = partition(a,i,j);
quickSort(a, i, mid-1);
quickSort(a, mid+1, j);
}
}
- partition函数
/**
*构造分割点,使得分割点左边元素都小于分割点,右边元素都大于分割点。
* @param a 待排序数组
* @param low 本次寻找分割点的区间中的最小坐标
* @param high 本次寻找分割点的区间中的最大坐标
* @return 分割点的坐标
*/
private static int partition(int[] a, int low, int high) {
int biao = a[low];
while(low < high) {
while (low < high && a[high] >= biao)
high--;
if (low < high)
a[low++] = a[high];
while (low < high && a[low] <= biao)
low++;
if (low < high)
a[high--] = a[low];
}
a[low] = biao;
return low;
}
- 生成指定个数的随机数数组
private static int[] getRandomArr(int numberCount) {
int a[] = new int[numberCount];
for (int i = 0; i < a.length; i++) {
a[i] = (int) (1+(int)(Math.random()*(numberCount*5-1)));//生成从1~numberCount*5的随机数,这个区间可以自己设置
}
return a;
}
4.main函数:
public static void main(String[] args) {
int n = 30;
int a[] = getRandomArr(n);//数组个数
System.out.println("defore:");
System.out.println(Arrays.toString(a));
quickSort(a,0,n-1);
System.out.println("after:");
System.out.println(Arrays.toString(a));
}
- 完整版:
package main.java.test;
import java.util.Arrays;
import java.util.Date;
/**
* @author 12556
*
*/
public class QuickSort {
private static int[] getRandomArr(int numberCount) {
int a[] = new int[numberCount];
for (int i = 0; i < a.length; i++) {
a[i] = (int) (1+(int)(Math.random()*(numberCount*5-1)));
}
return a;
}
private static void quickSort(int[] a, int i, int j) {if (i < j) {
int mid = partition(a,i,j);
quickSort(a, i, mid-1);
quickSort(a, mid+1, j);
}
}
/**
*构造分割点,使得分割点左边元素都小于分割点,右边元素都大于分割点。
* @param a 待排序数组
* @param low 本次寻找分割点的区间中的最小坐标
* @param high 本次寻找分割点的区间中的最大坐标
* @return 分割点的坐标
*/
private static int partition(int[] a, int low, int high) {
int biao = a[low];
while(low < high) {
while (low < high && a[high] >= biao)
high--;
if (low < high)
a[low++] = a[high];
while (low < high && a[low] <= biao)
low++;
if (low < high)
a[high--] = a[low];
}
a[low] = biao;
return low;
}
}
public static void main(String[] args) {
int n = 30;
int a[] = getRandomArr(n);//数组个数
System.out.println("defore:");
System.out.println(Arrays.toString(a));
// long startTime = System.nanoTime();
quickSort(a,0,n-1);
// long duration = System.nanoTime()-startTime;
System.out.println("after:");
System.out.println(Arrays.toString(a));
// System.out.println("duration(ms)="+duration/(1000000*1.0));
}