Chapter 7-2 2
Chapter 7-2 2
Report
(2024-2025-1)
Departmen
Student ID 23172503
2. Write a routine that implement quicksort, using median-of-three partitioning and a cutoff
of 3 (cutoff part use inserting sort). Besides, construct a permutation of 20 elements that
is as bad as possible.
1.
#include <stdio.h>
// Move elements of arr[0..i-1] that are greater than `key` to one position
ahead
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j]; // Shift the larger element one position to the right
j--; // Move to the previous element
}
int main() {
// Define an array to be sorted
int arr[] = {12, 11, 13, 5, 6};
// Calculate the number of elements in the array
int n = sizeof(arr) / sizeof(arr[0]);
Screenshots:
2.
#include <stdio.h>
arr[j + 1] = key;
}
}
// Function to find the median of three elements and return the pivot index
int medianOfThree(int arr[], int low, int high) {
int mid = low + (high - low) / 2;
int i = low - 1;
for (int j = low; j < high; j++) {
if (arr[j] <= pivot) {
i++;
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
return i + 1;
}
int main() {
// Create an array of 20 elements with the worst-case permutation
int arr[20];
generateWorstCasePermutation(arr, 20);
return 0;
}