Advertisement
tampurus

2.3 Quicksort

Jan 4th, 2022 (edited)
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.04 KB | None | 0 0
  1. #include <stdio.h>
  2.  
  3. void swap(int *a,int *b){
  4.     int temp = *a;
  5.     *a = *b;
  6.     *b = temp;
  7. }
  8. int Partition (int arr[], int low, int high)
  9. {
  10.     int pivot = arr[high]; // pivot
  11.     int i = (low - 1); // Index of smaller element and indicates the right position of pivot found so far
  12.  
  13.     for (int j = low; j <= high - 1; j++)
  14.     {
  15.         // If current element is smaller than the pivot
  16.         if (arr[j] < pivot)
  17.         {
  18.             i++; // increment index of smaller element
  19.             swap(&arr[i], &arr[j]);
  20.         }
  21.     }
  22.     swap(&arr[i + 1], &arr[high]);
  23.     return (i + 1);
  24. }
  25.  
  26. void Quicksort(int arr[], int low, int high)
  27. {
  28.     if (low < high)
  29.     {
  30.         int pi = Partition(arr, low, high);
  31.         Quicksort(arr, low, pi-1);
  32.         Quicksort(arr, pi + 1, high);
  33.     }
  34. }
  35.  
  36. int main()
  37. {
  38.     int n;
  39.     scanf("%d", &n);
  40.     int arr[n];
  41.     for (int i = 0; i < n; i++) scanf("%d", &arr[i]);
  42.  
  43.     Quicksort(arr, 0, n - 1);
  44.  
  45.     for(int i=0 ; i<n ; i++) printf("%d ",arr[i]);
  46.  
  47.     return 0;
  48. }
  49.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement