When i choose pivot the first element of list this code works but for example i want to make last element pivot and i wanna make minumum change in this code so i add swap(arr[high],arr[low]) before pivot=arr[low] i just change the value of low to high.But program stopped run.I don't know why this isn't work.
int partition(int low, int high, int arr[])
{
int pivot = arr[low];
int i = low;
for (int j = low + 1; j <= high; ++j)
{
if (arr[j] < pivot)
{
++i;
swap(arr[j], arr[i]);
}
}
swap(arr[low], arr[i]);
return i;
}
void quickSort(int low, int high, int arr[])
{
if (low < high)
{
int pivot = partition(low, high, arr);
quickSort(low, pivot, arr);
quickSort(pivot + 1, high, arr);
}
}
i just change the value of low to high
If you mean you made this change:
int pivot = arr[high]; // was arr[low]
then the code needs to be updated elsewhere. Typical lomuto partion scheme example:
int Partition(int arr[], int low, int high)
{
int pivot = arr[high];
int i = low;
for (int j = low; j < high; ++j)
{
if (arr[j] < pivot)
{
std::swap(arr[j], arr[i]);
++i;
}
}
std::swap(arr[i], arr[high]);
return i;
}
void QuickSort(int arr[], int low, int high)
{
if (low < high)
{
int pivot = Partition(arr, low, high);
QuickSort(arr, low, pivot-1);
QuickSort(arr, pivot + 1, high);
}
}