java 快排非递归_java实现递归快排和非递归快排

这篇博客介绍了一种将快速排序与插入排序结合的算法实现。通过使用随机数选择枢轴元素,并在子数组大小小于一定阈值时切换到插入排序,以提高排序效率。这种方法利用了两种排序算法的优势,提高了在各种输入情况下的性能。
摘要由CSDN通过智能技术生成

package sort;

import java.util.Random;

public class QuickSort {

public static Random random = new Random(1000);

public static void exchange(int[] array, int i, int j) {

int temp = array[i];

array[i] = array[j];

array[j] = temp;

}

public static int getPivot(int[] array, int from, int to) {

int target = array[to];

int i = from - 1;

for (int j = from; j < to; j++) {

if (array[j] <= target) {

i++;

exchange(array, i, j);

}

}

exchange(array, i + 1, to);

return i + 1;

}

public static void insertSort(int[] L, int low, int high) {

int i, j, temp;

for (i = low + 1; i <= high; i++) {

if (L[i] < L[i - 1]) {

temp = L[i];

for (j = i - 1; L[j] > temp && j >= low; j--) {

L[j + 1] = L[j];

}

L[j + 1] = temp;

}

}

}

public static void noQuickSort(int[] array, int from, int to) {

int stack[] = new int[10000];

int top = 0;

int pivot = getPivot(array, from, to);

int temp = pivot + 1;

for (int i = pivot + 1; i < to + 1; i++) {

if (array[i] > array[temp]) {

temp = i;

}

}

stack[top++] = to;

stack[top++] = pivot;

exchange(array, temp, to);

for (;;) {

if ((pivot - from) > 20) {

pivot = getPivot(array, from, pivot - 1);

stack[top++] = pivot;

} else {

insertSort(array, from, pivot - 1);

from = pivot + 1;

if (top == 1) {

break;

}

pivot = stack[top - 2];

top--;

}

}

}

public static void quickSort(int[] array, int from, int to) {

if (from < to) {

int temp = from + (int) (Math.random() * (to - from));

exchange(array, temp, to);

int pivot = getPivot(array, from, to);

quickSort(array, from, pivot - 1);

quickSort(array, pivot + 1, to);

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值