// This is an insertion-sort program, created using Google Gemini. #include // --- Global Variables --- // Array to be sorted int input[5] = {8, 2, 5, 1, 4}; // Array to store the sorted result int output[5]; // Length of the arrays int array_length = 5; // --- Helper Functions --- /** * @brief Swaps two integer values using pointers. */ void swap(int* a, int* b) { int temp = *a; *a = *b; *b = temp; } /** * @brief Partitions the array for quicksort. * This implementation uses the Lomuto partition scheme, * choosing the last element as the pivot. * * @param arr The array to partition. * @param low The starting index of the partition. * @param high The ending index (and pivot index) of the partition. * @return The new index of the pivot after partitioning. */ int partition(int arr[], int low, int high) { // Choose the last element as the pivot int pivot = arr[high]; // Index of the smaller element int i = (low - 1); // Iterate from the start (low) to just before the pivot (high - 1) for (int j = low; j <= high - 1; j++) { // If the current element is smaller than the pivot if (arr[j] < pivot) { i++; // Increment the index for the "smaller" section swap(&arr[i], &arr[j]); // Move this element to the "smaller" section } } // Place the pivot in its correct sorted position swap(&arr[i + 1], &arr[high]); return (i + 1); // Return the pivot's new index } // --- Quicksort Main Function --- /** * @brief The main recursive quicksort function. * * @param arr The array to sort. * @param low The starting index of the section to sort. * @param high The ending index of the section to sort. */ void quickSort(int arr[], int low, int high) { if (low < high) { // Find the partitioning index 'pi' // arr[pi] is now in its correct sorted place int pi = partition(arr, low, high); // Recursively sort the elements before the partition quickSort(arr, low, pi - 1); // Recursively sort the elements after the partition quickSort(arr, pi + 1, high); } } /** * @brief Utility function to print an array. */ void printArray(int arr[], int size) { for (int i = 0; i < size; i++) { printf("%d ", arr[i]); } printf("\n"); } // --- Main Program Execution --- int main() { // Call quicksort on the global 'input' array // We pass 0 as the low index and (array_length - 1) as the high index quickSort(input, 0, array_length - 1); // Copy the now-sorted 'input' array into the 'output' array for (int i = 0; i < array_length; i++) { output[i] = input[i]; } // Print the final 'output' array printf("Sorted output array: \n"); printArray(output, array_length); return 0; }