Advertisement
Guest User

Untitled

a guest
May 2nd, 2016
51
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.96 KB | None | 0 0
  1. private int array[];
  2. private int length;
  3.  
  4. public void sort(int[] inputArr) {
  5.  
  6. if (inputArr.length == 0) {
  7. return;
  8. }
  9. this.array = inputArr;
  10. length = inputArr.length;
  11. quickSort(0, length - 1);
  12. }
  13.  
  14. private void quickSort(int lowerIndex, int higherIndex) {
  15.  
  16. int i = lowerIndex;
  17. int j = higherIndex;
  18. // calculate pivot number, I am taking pivot as middle index number
  19. int mid = array[(higherIndex-1)/2];
  20. // Divide into two arrays
  21.  
  22. int pivot = findMedian(array, i, mid, j);
  23. swap(pivot, 0);
  24.  
  25. while (i <= j) {
  26. /**
  27. * In each iteration, we will identify a number from left side which
  28. * is greater then the pivot value, and also we will identify a number
  29. * from right side which is less then the pivot value. Once the search
  30. * is done, then we exchange both numbers.
  31. */
  32. while (array[i] < mid) {
  33. i++;
  34. }
  35. while (array[j] > mid) {
  36. j--;
  37. }
  38. if (i <= j) {
  39. swap(i, j);
  40. //move index to next position on both sides
  41. i++;
  42. j--;
  43. }
  44. }
  45. // call quickSort() method recursively
  46. if (lowerIndex < j)
  47. quickSort(lowerIndex, j);
  48. if (i < higherIndex)
  49. quickSort(i, higherIndex);
  50. }
  51.  
  52. public static int findMedian (int[] array, int a, int b, int c) {
  53. if ((array[a] > array[b] && array[a] < array[c]) || (array[a] > array[c] && array[a] < array[b])) {
  54. return a;
  55. } else if ((array[b] > array[a] && array[b] < array[c]) || (array[b] > array[c] && array[b] < array[a])) {
  56. return b;
  57. }
  58. return c;
  59. }
  60.  
  61.  
  62. private void swap(int i, int j) {
  63. int temp = array[i];
  64. array[i] = array[j];
  65. array[j] = temp;
  66. }
  67.  
  68. public static void main(String a[]){
  69.  
  70. MyQuickSort sorter = new MyQuickSort();
  71. int[] input = {24,2,45,20,56,75,2,56,99,53,12};
  72. sorter.sort(input);
  73. for(int i:input){
  74. System.out.print(i);
  75. System.out.print(" ");
  76. }
  77. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement