• Source
    1. // simple C program for Quick Sort
    2. # include <stdio.h>
    3.  
    4. // to swap two numbers
    5. void swap(int* a, int* b)
    6. {
    7. int t = *a;
    8. *a = *b;
    9. *b = t;
    10. }
    11.  
    12. /*
    13.   a[] is the array, p is starting index, that is 0,
    14.   and r is the last index of array.
    15. */
    16. void quicksort(int a[], int p, int r)
    17. {
    18. if(p < r)
    19. {
    20. int q;
    21. q = partition(a, p, r);
    22. quicksort(a, p, q);
    23. quicksort(a, q+1, r);
    24. }
    25. }
    26.  
    27. int partition (int a[], int low, int high)
    28. {
    29. int pivot = arr[high]; // selecting last element as pivot
    30. int i = (low - 1); // index of smaller element
    31.  
    32. for (int j = low; j <= high- 1; j++)
    33. {
    34. // If current element is smaller than or equal to pivot
    35. if (arr[j] <= pivot)
    36. {
    37. i++; // increment index of smaller element
    38. swap(&arr[i], &arr[j]);
    39. }
    40. }
    41. swap(&arr[i + 1], &arr[high]);
    42. return (i + 1);
    43. }
    44.  
    45. // function to print the array
    46. void printArray(int a[], int size)
    47. {
    48. int i;
    49. for (i=0; i < size; i++)
    50. {
    51. printf("%d ", a[i]);
    52. }
    53. printf("\n");
    54. }
    55.  
    56. int main()
    57. {
    58. int arr[] = {9, 7, 5, 11, 12, 2, 14, 3, 10, 6};
    59. int n = sizeof(arr)/sizeof(arr[0]);
    60.  
    61. // call quickSort function
    62. quickSort(arr, 0, n-1);
    63.  
    64. printf("Sorted array: n");
    65. printArray(arr, n);
    66. return 0;
    67. }