Quick sort - The Best Sort in C language


SUBMITTED BY: Neutrino

DATE: Dec. 10, 2020, 3:44 a.m.

FORMAT: Text only

SIZE: 959 Bytes

HITS: 517

  1. #include<stdio.h>
  2. void swap(int* a, int* b)
  3. {
  4. int t = *a;
  5. *a = *b;
  6. *b = t;
  7. }
  8. int partition (int arr[], int low, int high)
  9. {
  10. int pivot = arr[high];
  11. int i = (low - 1);
  12. for (int j = low; j <= high- 1; j++)
  13. {
  14. if (arr[j] < pivot)
  15. {
  16. i++;
  17. swap(&arr[i], &arr[j]);
  18. }
  19. }
  20. swap(&arr[i + 1], &arr[high]);
  21. return (i + 1);
  22. }
  23. void quickSort(int arr[], int low, int high)
  24. {
  25. if (low < high)
  26. {
  27. int pi = partition(arr, low, high);
  28. quickSort(arr, low, pi - 1);
  29. quickSort(arr, pi + 1, high);
  30. }
  31. }
  32. void printArray(int arr[], int size)
  33. {
  34. int i;
  35. for (i=0; i < size; i++)
  36. printf("%d ", arr[i]);
  37. printf("\n");
  38. }
  39. int main()
  40. {
  41. int arr[100];
  42. int i,n;
  43. printf("\n Enter the no of elements in the array ");
  44. scanf("%d",&n);
  45. printf("\n Enter the elements :");
  46. for (i=0;i<n;i++)
  47. {scanf("%d",&arr[i]);}
  48. quickSort(arr, 0, n-1);
  49. printf("Sorted array: \n");
  50. printArray(arr, n);
  51. return 0;
  52. }

comments powered by Disqus