快速排序是较好的排序算法,但是只有将它用好的逻辑代码实现才能看出它的威力,本人用几种思维逻辑实现了快速排序,但是运行结果发现,同样是快速排序,不同实现方法运行效率差别相当大,现在把运行效率最好的代码共享。
import java.util.Random;
public class Sort {
private static int count = 0;
/**
* 快速排序的简单实现:
* 1、如果实位置大于0或者结束位置大于总长度时出现数组越界异常,否则转向2
* 2、如果其实位置大于等于结束位置,则返回原数组,否则转向3
* 3、以最后位置为参考位置,并将start位置赋予i,end-1位置赋予j,并且当i<=j时执行循环执行4
* 4、从j开始向前查找到第一个大于等于基准点的数据,找到后从i开始找小于等于基准点的数据,找到后如果符合i<j,则i,j位置数据互换。
* 5、将i和基准点的数据交换。
* 6、递归快速排序(i+1)->end的数据
* 7、快速排序 start->(i-1)的数据
* 8、返回排序后的数组
*
* @param arr
* 要排序的数组
* @param start
* 参与排序的数组的其实位置
* @param end
* 参与排序的数组结束位置
* @return int[] 排序后的数组
*/
public static int[] quickSort(int[] arr, int start, int end) {
count++;// 压栈次数
if (start < 0 || end > arr.length) {
throw new java.lang.ArrayIndexOutOfBoundsException();
} else if (start >= end) {
return arr;
}
int media = arr[end];
int i = start, j = end - 1;
while (i <= j) {
while (j >= i && arr[j] >= media) {
j--;
}
while (i <= j && arr[i] <= media) {
i++;
}
if (i < j) {
swap(arr, i, j);
}
}
swap(arr, i, end);
quickSort(arr, start, i - 1);// 较小数据快速排序
quickSort(arr, i + 1, end);// 较大数据快速排序
return arr;
}
/**
* 交换数组中的数据
*
* @param numbers
* 数组
* @param pos
* 要交换的数据在数组中的位置
* @param anotherPos
* 要交换的数据在数组中的位置
*/
private static void swap(int[] numbers, int pos, int anotherPos) {
int media = numbers[pos];
numbers[pos] = numbers[anotherPos];
numbers[anotherPos] = media;
}
public static void main(String args[]) {
int[] arr = new int[10000];
for (int i = 0; i < arr.length; i++) {// 生成5000个随机数
arr[i] = new Random().nextInt(50000);
}
long t = System.currentTimeMillis();
quickSort(arr, 0, arr.length - 1);// 快速排序
System.out.println("排序时间:" + (System.currentTimeMillis() - t));
System.out.println("压栈次数:" + count);
System.out.println("排序后数据:");
for (int i = 0; i < arr.length; i++) {// 循环打印排序后的结果,每行10个
System.out.print(arr[i] + ",");
if ((i + 1) % 10 == 0) {
System.out.print("\n");
}
}
}
}
快速排序源代码说明:
1、递归快速排序算法是采用不断压栈,所以本方法监控了压栈次数。栈的操作非常快,但是栈空间是有限的,所以基本上是空间换时间的做法。
2、如果数据量过大,栈的空间不能满足,可以选择和其它算法结合,折中速度及栈空间的使用。
只需要将
if (start < 0 || end > arr.length) {
throw new java.lang.ArrayIndexOutOfBoundsException();
} else if (start >= end) {
return arr;
}
修改为:
if (start < 0 || end > arr.length) {
throw new java.lang.ArrayIndexOutOfBoundsException();
} else if (start >= end) {
return arr;
}else if (start >= 8) {
return bubbleSort(arr,start,end)
}
注意:swap方法要用private 或者实用final限定符,编译器将进行编译优化,提高运行效率。具体请参考 final、private限定符的使用规则。