java 快速排序
import java.util.Comparator; import java.util.Random; public class QuickSort { public static final Random RND = new Random(); private static void swap(Object[] array, int i, int j) { Object tmp = array[i]; array[i] = array[j]; array[j] = tmp; } private static int partition(E[] array, int begin, int end, Comparator super E> cmp) { int index = begin + RND.nextInt(end - begin + 1); E pivot = array[index]; swap(array, index, end); for (int i = index = begin; i < end; ++ i) { if (cmp.compare(array[i], pivot) <= 0) { swap(array, index++, i); } } swap(array, index, end); return (index); } private static void qsort(E[] array, int begin, int end, Comparator super E> cmp) { if (end > begin) { int index = partition(array, begin, end, cmp); qsort(array, begin, index - 1, cmp); qsort(array, index + 1, end, cmp); } } public static void sort(E[] array, Comparator super E> cmp) { qsort(array, 0, array.length - 1, cmp); } public static void main(String args[]) { Integer array[]=new Integer[]{19, 1, 10, 14, 16, 4, 7, 9, 3, 2, 8, 5, 11}; sort(array,new IntComparator()); for(int i=0;istatic class IntComparator implements Comparator{//static必须 public int compare(Integer o1, Integer o2) { if(o1< o2){ return -1; }else if(o1 == o2){ return 0; }else{ return 1; } } } }
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
暂时没有评论,来抢沙发吧~