Question: #include using namespace std; int partition ( int arr [ ] , int left, int right ) { int pivot = _ _ _ ;

#include
using namespace std;
int partition(int arr[], int left, int right){
int pivot =___; //Task 3: consider the last element of the array as a pivot
int pIndex = left; //pIndex represents the actual index of the pivot in the sorted list
//set pIndex to the left index initailly
for(int i = left; i <___; i++){//Task 4
if (___<=___){//Task 5
swap(___,___); //Task 6: swap when an element <= pivot
pIndex =___; //Task 7
}
}
swap(arr[pIndex], arr[right]); //swap arr[end], i.e., the pivot, with the element at pIndex
// The previous line helps to place the pivot in its proper place in the sorted array
return ___; //Task 8
}
void quick_sort(int arr[], int left, int right){
if(left < right){
int pIndex = partition(arr, left, right);
quick_sort(arr,___,___); //Task 1: recursively call the function for the left subarray of the pivot
quick_sort(arr,___,___); //Task 2: recursively call the function for the right subarray of the pivot
}
}
// Print the array
void printArray(int arr[], int size){
for (int i =0; i < size; i++)
cout << arr[i]<<"";
cout << endl;
}
// Driver program
int main(){
int arr[]={16,55,12,-23,94,11,45,2,-64,7};
int size = sizeof(arr)/ sizeof(arr[0]);
cout << "Unsorted array: ";
printArray(arr, size);
quick_sort(arr,0, size -1);
cout << "Sorted array: ";
printArray(arr, size);
return 0;
} In this assignment, your task is to modify the existing Quick Sort code to randomly choose the pivot element, which can help improve the algorithm's performance in avoiding worst-case scenarios.
Tasks:
Modify the partition function to include a step that randomly selects a pivot index within the subarray range. You can use the rand() function along with proper indexing to achieve this.
Implement the randomized pivot selection in the partition function by swapping the randomly chosen pivot element with the last element of the subarray.

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!