Java实现的快速排序算法
2018-07-20 来源:open-open
import java.util.Arrays; 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 <E extends Comparable<? super E>> int partition(E[] array, int begin, int end) { 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 (array[i].compareTo(pivot) <= 0) { swap(array, index++, i); } } swap(array, index, end); return (index); } private static <E extends Comparable<? super E>> void qsort(E[] array, int begin, int end) { if (end > begin) { int index = partition(array, begin, end); qsort(array, begin, index - 1); qsort(array, index + 1, end); } } public static <E extends Comparable<? super E>> void sort(E[] array) { qsort(array, 0, array.length - 1); } // Example uses public static void main(String[] args) { Integer[] l1 = { 5, 1024, 1, 88, 0, 1024 }; System.out.println("l1 start:" + Arrays.toString(l1)); QuickSort.sort(l1); System.out.println("l1 sorted:" + Arrays.toString(l1)); String[] l2 = { "gamma", "beta", "alpha", "zoolander" }; System.out.println("l2 start:" + Arrays.toString(l2)); QuickSort.sort(l2); System.out.println("l2 sorted:" + Arrays.toString(l2)); } } Analogously to the Erlang solution above, a user-supplied {{Javadoc:SE|java/util|Comparator}} determines the partial ordering of array elements: 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 <E> int partition(E[] array, int begin, int end, Comparator<? super E> cmp) { int index = begin + RND.nextInt(end - begin + 1); Object 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 <E> 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 <E> void sort(E[] array, Comparator<? super E> cmp) { qsort(array, 0, array.length - 1, cmp); } }
标签: swap
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点!
本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。
最新资讯
热门推荐