一个快速排序程序

本文介绍了一种使用Java实现的快速排序算法,并提供了完整的源代码示例。该算法通过递归方式实现,支持自定义比较器,适用于不同类型的数组排序。
无意中看到一个游戏中有着快速排序的源代码,备份下
import java.util.comparator;public class quicksorter<type> extends sorter<type> {    public void sort(type[] array, int count, comparator<type> comparator) {        quicksort(array, 0, count - 1, comparator);    }                 // quicksort a[left] to a[right]    public void quicksort(type[] a, int left, int right, comparator<type> comparator) {        if (right <= left) return;        int i = partition(a, left, right, comparator);        quicksort(a, left, i - 1, comparator);        quicksort(a, i + 1, right, comparator);    }           // partition a[left] to a[right], assumes left < right    private int partition(type[] a, int left, int right, comparator<type> comparator) {        int i = left - 1;        int j = right;        while (true) {            while (comparator.compare(a[++i], a[right]) < 0) {     // find item on left to swap            }                              // a[right] acts as sentinel            while (comparator.compare(a[right], a[--j]) < 0) {    // find item on right to swap                if (j == left) {                     break;                 // don't go out-of-bounds                }            }            if (i >= j) {                break;                     // check if pointers cross            }            type swap = a[i];                 // swap two elements into place            a[i] = a[j];            a[j] = swap;        }        type swap = a[i]; // swap with partition element        a[i] = a[right];        a[right] = swap;        return i;    }}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值