Advertisement
Guest User

Untitled

a guest
Dec 15th, 2019
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.77 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <time.h>
  3. #include <stdlib.h>
  4.  
  5. void Swap(int* a, int* b)
  6. {
  7. int t = *a;
  8. *a = *b;
  9. *b = t;
  10. }
  11.  
  12. int partition(int arr[], int low, int high)
  13. {
  14. int pivot = arr[high]; // pivot
  15. int i = (low - 1); // Index of smaller element
  16.  
  17. for (int j = low; j <= high - 1; j++)
  18. {
  19. // If current element is smaller than the pivot
  20. if (arr[j] < pivot)
  21. {
  22. i++; // increment index of smaller element
  23. Swap(&arr[i], &arr[j]);
  24. }
  25. }
  26. Swap(&arr[i + 1], &arr[high]);
  27. return (i + 1);
  28. }
  29.  
  30. void QuickSort(int arr[], int low, int high)
  31. {
  32. if (low < high)
  33. {
  34. int pi = partition(arr, low, high);
  35.  
  36. QuickSort(arr, low, pi - 1);
  37. QuickSort(arr, pi + 1, high);
  38. }
  39. }
  40.  
  41. int Min(int arr[], int from, int size) {
  42. int minEl = arr[from];
  43. int minPos = from;
  44. for (int i = from; i < size; i++) {
  45. if (arr[i] < minEl) {
  46. minEl = arr[i];
  47. minPos = i;
  48. }
  49. }
  50. return minPos;
  51. }
  52.  
  53. void SelectionSort(int arr[], int size) {
  54. for (int i = 0; i < size - 1; i++) {
  55. Swap(&arr[i], &arr[Min(arr, i, size)]);
  56. }
  57. }
  58.  
  59. #define SIZE 10000
  60.  
  61. int main(void) {
  62. srand((unsigned int)time(NULL));
  63. int arr1[SIZE];
  64. int arr2[SIZE];
  65. for (int i = 0; i < SIZE; i++) {
  66. arr1[i] = rand() % 100;
  67. arr2[i] = arr1[i];
  68. }
  69.  
  70. clock_t start, end;
  71. start = clock();
  72. QuickSort(arr1, 0, SIZE - 1);
  73. end = clock();
  74. printf("Quick sort took %lf\n", ((double)end - (double)start) / 1000);
  75.  
  76. start = clock();
  77. SelectionSort(arr2, SIZE);
  78. end = clock();
  79. printf("Selection sort took %lf\n", ((double)end - (double)start) / 1000);
  80.  
  81. int sortedSame = 1;
  82. for (int i = 0; i < 10; i++) {
  83. if (arr1[i] != arr2[i]) {
  84. sortedSame = 0;
  85. printf("Error.\n");
  86. break;
  87. }
  88. }
  89. if (sortedSame) {
  90. printf("Arrays sorted equally.\n");
  91. }
  92.  
  93.  
  94. return;
  95. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement