Advertisement
Guest User

Untitled

a guest
Jun 27th, 2017
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.55 KB | None | 0 0
  1. class QuickSort
  2. {
  3. /* This function takes last element as pivot,
  4. places the pivot element at its correct
  5. position in sorted array, and places all
  6. smaller (smaller than pivot) to left of
  7. pivot and all greater elements to right
  8. of pivot */
  9. int partition(int arr[], int low, int high)
  10. {
  11. int pivot = arr[high];
  12. for(int i = low; i < high; i++) {
  13. if(arr[i] < pivot) {
  14. int temp = arr[i];
  15. arr[i] = arr[low];
  16. arr[low] = temp;
  17. low++;
  18. }
  19. }
  20.  
  21. int temp = pivot;
  22. arr[high] = arr[low];
  23. arr[low] = temp;
  24.  
  25. return low;
  26. }
  27.  
  28. /* The main function that implements QuickSort()
  29. arr[] --> Array to be sorted,
  30. low --> Starting index,
  31. high --> Ending index */
  32. void sort(int arr[], int low, int high)
  33. {
  34. if (low < high)
  35. {
  36. int pIndex = partition(arr, low, high);
  37. sort(arr, low, pIndex -1);
  38. sort(arr, pIndex + 1, high);
  39. }
  40. }
  41.  
  42. static void printArray(int arr[])
  43. {
  44. int n = arr.length;
  45. for (int i=0; i<n; ++i)
  46. System.out.print(arr[i]+" ");
  47. System.out.println();
  48. }
  49.  
  50. // Driver program
  51. public static void main(String args[])
  52. {
  53. int arr[] = {7, 2, 1, 6, 8, 5, 3, 4};
  54. int n = arr.length;
  55.  
  56. QuickSort ob = new QuickSort();
  57. ob.sort(arr, 0, n-1);
  58.  
  59. System.out.println("sorted array");
  60. printArray(arr);
  61. }
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement