fork download
  1. /* C implementation QuickSort */
  2. #include<stdio.h>
  3.  
  4. // A utility function to swap two elements
  5. void swap(int* a, int* b)
  6. {
  7. int t = *a;
  8. *a = *b;
  9. *b = t;
  10. }
  11.  
  12. /* This function takes last element as pivot, places
  13. the pivot element at its correct position in sorted
  14. array, and places all smaller (smaller than pivot)
  15. to left of pivot and all greater elements to right
  16. of pivot */
  17. int partition (int arr[], int low, int high)
  18. {
  19. int pivot = arr[high]; // pivot
  20. int i = (low - 1); // Index of smaller element
  21.  
  22. for (int j = low; j <= high- 1; j++)
  23. {
  24. // If current element is smaller than or
  25. // equal to pivot
  26. if (arr[j] <= pivot)
  27. {
  28. i++; // increment index of smaller element
  29. swap(&arr[i], &arr[j]);
  30. }
  31. }
  32. swap(&arr[i + 1], &arr[high]);
  33. return (i + 1);
  34. }
  35.  
  36. /* The main function that implements QuickSort
  37. arr[] --> Array to be sorted,
  38. low --> Starting index,
  39. high --> Ending index */
  40. void quickSort(int arr[], int low, int high)
  41. {
  42. if (low < high)
  43. {
  44. /* pi is partitioning index, arr[p] is now
  45. at right place */
  46. int pi = partition(arr, low, high);
  47.  
  48. // Separately sort elements before
  49. // partition and after partition
  50. quickSort(arr, low, pi - 1);
  51. quickSort(arr, pi + 1, high);
  52. }
  53. }
  54.  
  55. /* Function to print an array */
  56. void printArray(int arr[], int size)
  57. {
  58. int i;
  59. for (i=0; i < size; i++)
  60. printf("%d ", arr[i]);
  61. printf("");
  62. }
  63.  
  64. // Driver program to test above functions
  65. int main()
  66. {
  67. int arr[] = {10,7,6,12,3};
  68. int n = sizeof(arr)/sizeof(arr[0]);
  69. quickSort(arr, 0, n-1);
  70. printf("Sorted array: ");
  71. printArray(arr, n);
  72. return 0;
  73. }
  74.  
Success #stdin #stdout 0s 9432KB
stdin
Standard input is empty
stdout
Sorted array: 3 6 7 10 12