I have to create a program that takes an input file of unsorted numbers and outputs another file with the sorted numbers using Quicksort. This program has run fine under multiple test cases using integers. However, when I change the array format from ‘int’ to ‘double’ my program has trouble sorting the values correctly. The thing that perplexes me the most is that it is inconsistent. For example, the input “5,4,3,2,2.1” works fine, but the input “5,4,3,2.2,2.1” causes a seg fault. Any help would be appreciated. Thanks.
void swap(double *x, double *y)
{
double tmp;
tmp = *x;
*x = *y;
*y = tmp;
}
int pivot(int i, int j)
{
return ((i+j)/2);
}
void quickSort(double values[], int low, int high)
{
int start;
int end;
int k;
int p;
if (low < high)
{
p = pivot(low,high);
swap(&values[low],&values[p]);
k = values[low];
start = (low+1);
end = high;
while (start <= end)
{
while ((start <= high) && (values[start] <= k))
{
start++;
}
while ((end >= low) && (values[end] > k))
{
end--;
}
if (start < end)
{
swap(&values[start],&values[end]);
}
}
swap(&values[low],&values[end]);
quickSort(values,low,(end-1));
quickSort(values,(end+1),high);
}
}
int main()
{
...
quickSort(array, 0, (size+1);
...
return 0;
}
I think that
kshould be a double here 🙂