Answered step by step
Verified Expert Solution
Question
1 Approved Answer
In quicksort we pick an element as pivot and partitions the given array into two sub arrays under the condition of each elements of the
In quicksort we pick an element as pivot and partitions the given array into two sub arrays under the condition of each elements of the array greater and less than the pivot. There are many different versions of quicksort that pick pivot in different ways. 1. Always pick first element as pivot. 2. Always pick last element as pivot 3. Pick a random element as pivot 4. Pick median as pivot. We wll take option 2 to solve this problem. We start from the leftmost element under consideration and keep track of index of last the element smaller the pivot as mid. We then scan the array, and while scanning. if we find an element smaller than the pivot, we swap current element with arr[mid+1]. Otherwise we ignore current element and keep scanning. Like assignment 3, we will break our implementation into 3 separate functions and use them together at the end. First, write a function called swap, which simply swaps the current element with arrli]. a) void swap(int arr[l, int i, int j) // swaps arr[i] and arrj] b) The key process in quick sort is partition(). This function takes last element as pivot places the pivot element at its correct position in the sorted array and places all elements smaller than the pivot to left of pivot and all greater elements to right. int partition(int arrl], int first, int last) // pivot (element to be placed at the "middle" position); int pivot-arr[last]; // initialize and keep track of the last processed element smaller than pivot; // use the mid variable from lecture slides on the partition function // scan array, and swap if current element is smaller than or equal to pivot; / use your swap from step 1 // (remember to increment index of smaller element;) // return the correct index of pivot Page 1 of3 c) Finally, write a recursive quick sort function, called quickSortR. This function would find the partitioning index using the partition function from step 2. And separately sort elements before partition and after partition. // Post: arr[first.last] are sorted void quickSortR (int arr int first, int last) // See code from the lecture on quicksort void main) int arr[14]488888, 3, 5, e, 23, 12124, 6, 7, 2, 1121, e, 92, 5, 8) quickSortR(arr, e, 13); for (int printf( "arr[Kd] i- 8; i
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started