fork download
  1. #include <stdio.h>
  2. #include <time.h>
  3.  
  4. // Quicksort implementation as per Session 3 logic [cite: 13, 77]
  5. int partition(int arr[], int low, int high) {
  6. int pivot = arr[high]; // Choosing the last element as pivot [cite: 77]
  7. int i = (low - 1);
  8. for (int j = low; j < high; j++) {
  9. // If current element is smaller than or equal to pivot [cite: 77]
  10. if (arr[j] <= pivot) {
  11. i++;
  12. // Swap arr[i] and arr[j] [cite: 77]
  13. int temp = arr[i];
  14. arr[i] = arr[j];
  15. arr[j] = temp;
  16. }
  17. }
  18. // Final pivot swap to place it in the sorted position [cite: 77]
  19. int temp = arr[i + 1];
  20. arr[i + 1] = arr[high];
  21. arr[high] = temp;
  22. return (i + 1);
  23. }
  24.  
  25. void quickSort(int arr[], int low, int high) {
  26. if (low < high) {
  27. // Find pivot index such that smaller elements are on left [cite: 77]
  28. int pi = partition(arr, low, high);
  29. quickSort(arr, low, pi - 1);
  30. quickSort(arr, pi + 1, high);
  31. }
  32. }
  33.  
  34.  
  35. int main() {
  36. int n = 5000; // You can change this to 5000 or 10000 for your report
  37. int arr[n];
  38. clock_t start, end;
  39.  
  40. // Seed the random number generator
  41. srand(time(0));
  42.  
  43. // Fill the array with random numbers as per lab manual guidelines
  44. for (int i = 0; i < n; i++) {
  45. arr[i] = rand() % 10000;
  46. }
  47.  
  48. printf("Sorting %d elements using Quicksort...\n", n);
  49.  
  50. // Capture start time
  51. start = clock();
  52.  
  53. // Call the function (ensure your parameters match your manual's quickSort)
  54. quickSort(arr, 0, n - 1);
  55.  
  56. // Capture end time
  57. end = clock();
  58.  
  59. double time_taken = ((double)(end - start)) / CLOCKS_PER_SEC;
  60.  
  61. printf("Execution Successful!\n");
  62. printf("Time Taken: %f seconds\n", time_taken);
  63.  
  64. return 0;
  65. }
Success #stdin #stdout 0s 5320KB
stdin
Standard input is empty
stdout
Sorting 5000 elements using Quicksort...
Execution Successful!
Time Taken: 0.000000 seconds