Advertisement
Guest User

Untitled

a guest
Jul 21st, 2019
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.33 KB | None | 0 0
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. #include<time.h>
  4. int swap;
  5. void bubble_sort(int a[], int n)
  6. {
  7. int i,j,temp;
  8. swap=0;
  9. for(i=0; i<n; i++)
  10. {
  11. for(j=0; j<n-i-1; j++)
  12. {
  13. if(a[j]>a[j+1])
  14. {
  15. temp = a[j];
  16. a[j] = a[j+1];
  17. a[j+1] = temp;
  18. swap++;
  19. }
  20. }
  21. }
  22. }
  23.  
  24. void insertion_sort(int a[],int n)
  25. {
  26. int i,j,temp;
  27. swap=0;
  28. for(i=0; i<n; i++)
  29. {
  30.  
  31. j=i;
  32. while(j>=0&&a[j]>a[j+1])
  33. {
  34. temp = a[j];
  35. a[j] = a[j+1];
  36. a[j+1] = temp;
  37. j--;
  38. swap++;
  39. }
  40. }
  41.  
  42. }
  43. void selection_sort(int a[],int n)
  44. {
  45. int i,j,temp,mini;
  46. swap=0;
  47. for(i=0; i<n-1; i++)
  48. {
  49. mini=i;
  50. for(j=i+1; j<n; j++)
  51. {
  52. if(a[mini]>a[j])
  53. {mini=j;
  54. }
  55.  
  56. if(mini>i)
  57. {
  58. temp=a[mini];
  59. a[mini]=a[i];
  60. a[i]=temp;
  61. swap++;
  62.  
  63. }
  64. }
  65. }
  66. }
  67. int main()
  68. {
  69. int arr[500005];
  70. int len, i;
  71. clock_t start_time, end_time;
  72. double bubble_time;
  73. double selection_time;
  74. double insertion_time;
  75.  
  76. printf("Enter Array Length: ");
  77. scanf("%d", &len);
  78.  
  79. srand(time(0));
  80. for(i=0; i<len; i++)
  81. {
  82. arr[i]=rand()%100+1;
  83. }
  84.  
  85. start_time = clock();
  86. selection_sort(arr,len);
  87. end_time = clock();
  88.  
  89. selection_time = (double)(end_time-start_time)/CLOCKS_PER_SEC;
  90. printf("\nTime for selection sort 1000: %lf\n",selection_time);
  91. printf("swap = %d\n",swap);
  92.  
  93.  
  94.  
  95. for(i=0; i<len; i++)
  96. {
  97. arr[i]=rand()%100+1;
  98. }
  99.  
  100. start_time = clock();
  101. bubble_sort(arr,len);
  102. end_time = clock();
  103.  
  104. bubble_time = (double)(end_time-start_time)/CLOCKS_PER_SEC;
  105.  
  106. printf("Time for bubble sort: %lf\n",bubble_time);
  107. printf("swap = %d\n",swap);
  108. ///////////
  109.  
  110. for(i=0; i<len; i++)
  111. {
  112. arr[i]=rand()%100+1;
  113. }
  114. start_time = clock();
  115. insertion_sort(arr,len);
  116. end_time = clock();
  117.  
  118. insertion_time = (double)(end_time-start_time)/CLOCKS_PER_SEC;
  119. printf("\nTime for insertion sort 1000: %lf\n",insertion_time);
  120. printf("swap = %d\n",swap);
  121. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement