I wrote this lomuto-type function to use for quick sort, but it didn't work. Segmentation fault occurred in run-time. Where is my mistake?
int partition(int *a, int low, int high)
{
int pos = low, i, pivot = a[low], temp;
for (i = low + 1; i <= high; i++)
if(a[i] <= pivot) {
pos++;
temp = a[pos];
a[pos] = a[i];
a[i] = temp;
}
return pos;
}
void quickS(int *a, int low, int high)
{
while (low < high) {
int pivot = partition(a, low, high);
quickS(a, low, pivot - 1);
low = pivot + 1;
}
}
Try this:
void swap(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}
int partition(int data[], int l, int h)
{
int i;
int p;
int firsthigh;
p = h;
firsthigh = l;
for (i = l; i < h; ++i)
{
if (data[i] < data[p])
{
swap(&data[i], &data[firsthigh]);
firsthigh++;
}
}
swap(&data[p], &data[firsthigh]);
return firsthigh;
}
pivot(a[low]) seems to be there is a need to exchange.
Code for verification:
#include<stdio.h>
int partition(int *a, int low, int high){
int pos = low, i, pivot = a[low], temp;
for (i = low + 1; i <= high; i++)
if(a[i] <= pivot) {
pos++;
temp = a[pos];
a[pos] = a[i];
a[i] = temp;
}
return pos;
}
int main(){
int data[] = { 10, 1, 2, 3 };
int i, retvalue;
retvalue = partition(data, 0, 4-1);
printf("%d\n", retvalue);
for(i = 0; i< 4; ++i)
printf("%d ", data[i]);//10 1 2 3 : N/C
printf("\n");
return 0;
}
It is believed that if the partition function such suspect that the cause a stack overflow, and then repeat the call does not work correctly.
try like this
int partition (int arr[], int low, int high )
{
int x = arr[high];
int i = (low - 1);
for (int j = l; j <= high- 1; j++)
{
if (arr[j] <= x)
{
i++;
swap (&arr[i], &arr[j]);
}
}
swap (&arr[i + 1], &arr[high]);
return (i + 1);
}
void quickSort(int A[], int low, int high)
{
if (low < high)
{
int p = partition(A, low, high);
quickSort(A, low, p - 1);
quickSort(A, p + 1, high);
}
}
在获得正确的枢轴位置之后,需要将枢轴放置在该位置,然后返回该位置。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.