Advertisement
kiubia

OSTATNIE_QUICK_SORT_V-KSZTAŁTNIE

Mar 31st, 2020
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.41 KB | None | 0 0
  1. // An iterative implementation of quick sort
  2. #include <stdio.h>
  3. #include<time.h>
  4. // A utility function to swap two elements
  5. void swap(int* a, int* b)
  6. {
  7. int t = *a;
  8. *a = *b;
  9. *b = t;
  10. }
  11.  
  12. /* This function is same in both iterative and recursive*/
  13. int partition(int arr[], int l, int h)
  14. {
  15. int x = arr[h];
  16. int i = (l - 1);
  17.  
  18. for (int j = l; j <= h - 1; j++) {
  19. if (arr[j] <= x) {
  20. i++;
  21. swap(&arr[i], &arr[j]);
  22. }
  23. }
  24. swap(&arr[i + 1], &arr[h]);
  25. return (i + 1);
  26. }
  27.  
  28. /* A[] --> Array to be sorted,
  29. l --> Starting index,
  30. h --> Ending index */
  31. void quickSortIterative(int arr[], int l, int h)
  32. {
  33. // Create an auxiliary stack
  34. int stack[h - l + 1];
  35.  
  36. // initialize top of stack
  37. int top = -1;
  38.  
  39. // push initial values of l and h to stack
  40. stack[++top] = l;
  41. stack[++top] = h;
  42.  
  43. // Keep popping from stack while is not empty
  44. while (top >= 0) {
  45. // Pop h and l
  46. h = stack[top--];
  47. l = stack[top--];
  48.  
  49. // Set pivot element at its correct position
  50. // in sorted array
  51. int p = partition(arr, l, h);
  52.  
  53. // If there are elements on left side of pivot,
  54. // then push left side to stack
  55. if (p - 1 > l) {
  56. stack[++top] = l;
  57. stack[++top] = p - 1;
  58. }
  59.  
  60. // If there are elements on right side of pivot,
  61. // then push right side to stack
  62. if (p + 1 < h) {
  63. stack[++top] = p + 1;
  64. stack[++top] = h;
  65. }
  66. }
  67. }
  68.  
  69. // A utility function to print contents of arr
  70. void printArr(int arr[], int n)
  71. {
  72. int i;
  73. for (i = 0; i < n; ++i)
  74. printf("%d ", arr[i]);
  75. }
  76.  
  77. // Driver program to test above functions
  78. clock_t start, stop;
  79. double czas;
  80. int main()
  81. {
  82. int x=90000;
  83. int y=x/2;
  84. int j=x;
  85. int i=0;
  86. int arr[x+1];
  87. for (i=0;i<=y;i++)
  88. {
  89. arr[i]=j--;
  90. //printf("TABELA: %d\n",arr[i]);
  91. }
  92. for (i=y;i<=x;i++)//A-kształtna
  93. {
  94. arr[i]= i;
  95. //printf("TABELA: %d\n",arr[i]);
  96.  
  97. }
  98.  
  99. int n = sizeof(arr) / sizeof(*arr);
  100. start = clock();
  101. quickSortIterative(arr, 0, n - 1);
  102. printArr(arr, n);
  103. stop = clock();
  104. czas= (double) (stop-start)/CLOCKS_PER_SEC;
  105. printf("Czas QS: %f\n",czas);
  106.  
  107. return 0;
  108. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement