Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I am implementing quicksort, but for some reason I can\'t pinpoint where I\'m ge

ID: 3536968 • Letter: I

Question

I am implementing quicksort, but for some reason I can't pinpoint where I'm getting an error. If someone can help me debug, I'll be thankful.



#include <iostream>

#include <array>


using namespace std;

int arr[] = {7, 3, 8, 54, 23, 4, 9, 26};


int quicksort_partition(int arr[], int left, int right, int pivotIndex){

int pivotValue = arr[pivotIndex];

int temp;

int temp2;

temp = arr[pivotIndex];

arr[pivotIndex] = arr[right];

arr[right] = temp;

int storeIndex = left;

for (int i = left; i < right; i++){

if (arr[i] <= pivotValue){

temp2 = arr[i];

arr[i] = arr[storeIndex];

arr[storeIndex] = temp2;

storeIndex++;

}

}

int temp3;

temp3 = arr[storeIndex];

arr[storeIndex] = arr[right];

arr[right] = temp3;

return storeIndex;

}


void quicksort(int arr[], int left, int right){

if (left < right){

int pivotIndex = (left+right)/2;

int pivotNewIndex = quicksort_partition(arr, 0, sizeof(arr)/sizeof(int) - 1, pivotIndex);

quicksort(arr, left, pivotNewIndex-1);

quicksort(arr, pivotNewIndex+1, right);


}

}


int main(){


quicksort(arr, 0, sizeof(arr)/sizeof(int) - 1);

for (int i = 0; i < sizeof(arr)/sizeof(int); i++)

cout << arr[i] <<" ";

system("pause");

}

Explanation / Answer

// your modified versionof code ,and it is working fine after some editing and adding few lines of code, just check it.



#include <iostream>


using namespace std;

int arr[] = {7, 3, 8, 54, 23, 4, 9, 26};


int quicksort_partition(int arr[], int left, int right, int pivotIndex)

{

int pivotValue = arr[pivotIndex];

int temp;

temp = arr[pivotIndex];

arr[pivotIndex] = arr[right];

arr[right] = temp;

int storeIndex = left;

for (int i = left; i < right; i++)

{

if (arr[i] <= pivotValue)

{

temp = arr[i];

arr[i] = arr[storeIndex];

arr[storeIndex] = temp;

storeIndex++;

}

}

temp = arr[storeIndex];

arr[storeIndex] = arr[right];

arr[right] = temp;

return storeIndex;

}


void quicksort(int arr[], int left, int right)

{

if (left < right)

{

int pivotIndex = (left+right)/2;

int pivotNewIndex = quicksort_partition(arr, left,right, pivotIndex);

quicksort(arr, left, pivotNewIndex-1);

quicksort(arr, pivotNewIndex+1, right);


}

}



int main()

{


quicksort(arr, 0, sizeof(arr)/sizeof(int) - 1);

for (int i = 0; i < sizeof(arr)/sizeof(int); i++)

cout << arr[i] <<" ";

system("pause");

}