Advertisement
Guest User

Untitled

a guest
Dec 5th, 2020
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.79 KB | None | 0 0
  1. // Java program for implementation of QuickSort
  2. class QuickSort
  3. {
  4.     /* This function takes last element as pivot,
  5.     places the pivot element at its correct
  6.     position in sorted array, and places all
  7.     smaller (smaller than pivot) to left of
  8.     pivot and all greater elements to right
  9.     of pivot */
  10.     int partition(int arr[], int low, int high)
  11.     {
  12.         int pivot = arr[high];
  13.         int i = (low-1); // index of smaller element
  14.         for (int j=low; j<high; j++)
  15.         {
  16.             // If current element is smaller than the pivot
  17.             if (arr[j] < pivot)
  18.             {
  19.                 i++;
  20.  
  21.                 // swap arr[i] and arr[j]
  22.                 int temp = arr[i];
  23.                 arr[i] = arr[j];
  24.                 arr[j] = temp;
  25.             }
  26.         }
  27.  
  28.         // swap arr[i+1] and arr[high] (or pivot)
  29.         int temp = arr[i+1];
  30.         arr[i+1] = arr[high];
  31.         arr[high] = temp;
  32.  
  33.         return i+1;
  34.     }
  35.  
  36.  
  37.     /* The main function that implements QuickSort()
  38.     arr[] --> Array to be sorted,
  39.     low --> Starting index,
  40.     high --> Ending index */
  41.     void sort(int arr[], int low, int high)
  42.     {
  43.         if (low < high)
  44.         {
  45.             /* pi is partitioning index, arr[pi] is
  46.             now at right place */
  47.             int pi = partition(arr, low, high);
  48.  
  49.             // Recursively sort elements before
  50.             // partition and after partition
  51.             sort(arr, low, pi-1);
  52.             sort(arr, pi+1, high);
  53.         }
  54.     }
  55.  
  56.     /* A utility function to print array of size n */
  57.     static void printArray(int arr[])
  58.     {
  59.         int n = arr.length;
  60.         for (int i=0; i<n; ++i)
  61.             System.out.print(arr[i]+" ");
  62.         System.out.println();
  63.     }
  64.  
  65.     // Driver program
  66.     public static void main(String args[])
  67.     {
  68.         int arr[] = {10, 7, 8, 9, 1, 5};
  69.         int n = arr.length;
  70.  
  71.         QuickSort ob = new QuickSort();
  72.         ob.sort(arr, 0, n-1);
  73.  
  74.         System.out.println("sorted array");
  75.         printArray(arr);
  76.     }
  77. }
  78. /*This code is contributed by Rajat Mishra */
  79.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement