fork download
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. #include<time.h>
  4. int count=0;
  5. int partition(int a[], int low,int high)
  6. {
  7. int pivot=a[low],temp,i=low+1,j=high;
  8. while(1)
  9. {
  10. //Traverse i from left to right, segregating element of left group
  11. while(i<=high && a[i]<=pivot)//a[i]<=pivot used for avoiding multiple duplicates
  12. {
  13. i++; count++;
  14. }
  15. //Traverse j from right to left, segregating element of right group
  16. while(j>0 && a[j]>pivot)
  17. {
  18. j--; count++;
  19. }
  20. count+=2;
  21. //If grouping is incomplete
  22. if(i<j)
  23. {
  24. temp = a[i];
  25. a[i] = a[j];
  26. a[j] =temp;
  27. }
  28. else if(i>j)//If grouping is completed
  29. {
  30. temp = a[low];
  31. a[low] = a[j];
  32. a[j] = temp;
  33. return j;
  34. }
  35. else //Duplicate of Pivot found
  36. return j;
  37. }
  38. }
  39. void quicksort(int a[],int low, int high)
  40. {
  41. int s;
  42. if(low<high)
  43. {
  44. //partition to place pivot element in between left and right group
  45. s = partition(a,low,high);
  46. quicksort(a,low,s-1);
  47. quicksort(a,s+1,high);
  48. }
  49. }
  50. int main()
  51. {
  52. int a[10000],n;
  53. printf("Enter the number of elements in an array:");
  54. scanf("%d",&n);
  55. printf("All the elements:");
  56. srand(time(0));
  57. for(int i=0;i<n;i++)
  58. {
  59. a[i]=rand();
  60. printf("%d ",a[i]);
  61. }
  62. quicksort(a,0,n-1);
  63. printf("\nAfter sorting\n");
  64. for(int i=0;i<n;i++)
  65. printf("%d ", a[i]);
  66. printf("\nNumber of basic operations = %d\n",count);
  67. }
Success #stdin #stdout 0.01s 5276KB
stdin
Standard input is empty
stdout
Enter the number of elements in an array:All the elements:
After sorting

Number of basic operations = 0