Advertisement
Guest User

Untitled

a guest
Feb 19th, 2019
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.38 KB | None | 0 0
  1. import java.util.Random;
  2.  
  3. public class BasicTraining {
  4.  
  5. /**
  6. * Sort the array using quick sort, this must be:
  7. *
  8. * in-place (no temporary arrays)
  9. * O(n log n)
  10. *
  11. * @param array
  12. * @return a sorted array
  13. */
  14.  
  15.  
  16. public static <T extends Comparable<? super T>> void quickSortHelper(T[] array) {
  17.  
  18. int pivotIndex = 0;
  19. T pivotObject = array[pivotIndex];
  20. T temp = array[array.length - 1];
  21. array[array.length - 1] = array[0];
  22. array[0] = temp;
  23.  
  24. int keepTrack = 0;
  25. for(int i = 0; i < array.length; i++){
  26. if(pivotObject.compareTo(array[i]) > 0){
  27. T temp2 = array[keepTrack];
  28. array[keepTrack] = array[i];
  29. array[i] = temp2;
  30. keepTrack = keepTrack + 1;
  31. }
  32. }
  33.  
  34. T temp3 = array[keepTrack];
  35. array[keepTrack] = array[array.length - 1];
  36. array[array.length - 1] = temp3;
  37.  
  38. }
  39.  
  40. public static <T extends Comparable<? super T>> T[] quickSort(T[] array) {
  41. for(int i = 0; i < array.length; i++){
  42. quickSortHelper(array);
  43. }
  44. return array;
  45. }
  46.  
  47. public static void main(String[] args) {
  48. Integer[] arr = {6, 3, 9, 2, 8, 7};
  49. Integer[] sorted = quickSort(arr);
  50. for(Integer i : sorted) {
  51. System.out.println(i);
  52. }
  53.  
  54.  
  55. }
  56.  
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement