The original question was Write the following two generic methods using quick so
ID: 441245 • Letter: T
Question
The original question was Write the following two generic methods using quick sort. Thefirst method sorts the elements using theComparable interface and the second uses theComparator interface public static > voidquickSort(E[] list) public static void quickSort(E[] list, Comparator<? super E?> comparator) 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); Object pivot = array[index]; swap(array, index, end); for (int i = index = begin; i < end; ++ i) { if (cmp.compare(array[i], pivot ) ) { 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[] 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)); } }Explanation / Answer
When I run your code in eclipse it shows show many errors. it cannot identify " E[ ] ". Please check it. Refer this for more help http://www.java2s.com/Code/Java/CollectionsDataStructure/Quicksortimplementationforsortingarrays.htm
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.