fork download
  1. #include<stdio.h>
  2. //Function to swap twp numbers
  3. void swap(int*a,int*b)
  4. {
  5. int temp=*a;
  6. *a=*b;
  7. *b=temp;
  8. }
  9. //Partition function using first element as pivot
  10. int partition(int arr[],int low,int high)
  11. {
  12. int pivot=arr[low];//choosing 1st element as pivot
  13.  
  14. int i=low=1;
  15. int j=high;
  16. while(1)
  17. {
  18. while(i<=high&&arr[i]<=pivot)
  19. i++;
  20. while(j>=low&&arr[j]>pivot)
  21. j--;
  22. if(i<j)
  23. {
  24. swap(&arr[i],&arr[j]);
  25. }
  26. else
  27. {
  28. break;
  29. }
  30. }
  31. swap(&arr[low],&arr[j]);//place pivot in correct position
  32. return j;
  33. }
  34. //Quick sort function
  35. void quickSort(int arr[],int low,int high)
  36. {
  37. if(low<high)
  38. {
  39. int pi=partition(arr,low,high);
  40. //Recursively sort elemnts before amd after partition
  41. quickSort(arr,low,pi-1);
  42. quickSort(arr,pi+1,high);
  43. }
  44. }
  45. //drive code
  46. int main()
  47. {
  48. int arr[]={34,7,23,32,5,62};
  49. int n=sizeof(arr)/sizeof(arr[0]);
  50. printf("Unsorted array:");
  51. for (int i=0;i<n;i++)
  52. printf("%d",arr[i]);
  53. quickSort(arr,0,n-1);
  54. printf("\n Sorted array:");
  55. for(int i=0;i<n;i++)
  56. printf("%d",arr[i]);
  57. return 0;
  58. }
Success #stdin #stdout 0.01s 5284KB
stdin
45
stdout
Unsorted array:3472332562
 Sorted array:3423325762