一个快速排序程序
无意中看到一个游戏中有着快速排序的源代码,备份下
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; }}