[英]Implementing Quicksort for an array of strings in C - why am I getting SIGABRT error?
我正在按照本教程在C中实现Quicksort,但是它假定要对整数数组进行排序,而我正在尝试对字符串数组进行排序,据我所知,这是字符数组或char array[][]
。
这是我最后的实现:
void quicksort(char array[100][100], int firstIndex, int lastIndex) {
int pivotIndex, index1, index2;
char temp[100];
if (firstIndex < lastIndex) {
pivotIndex = firstIndex;
index1 = firstIndex;
index2 = lastIndex;
//Sorting in Ascending order with quick sort
while(index1 < index2)
{
while(strcmp(array[index1], array[pivotIndex]) <= 0 && index1 < lastIndex)
{
index1++;
}
while(strcmp(array[index2], array[pivotIndex]) > 0)
{
index2--;
}
if(index1<index2)
{
//Swapping opertation
strcpy(temp, array[index1]);
strcpy(array[index1], array[index2]);
strcpy(array[index2], temp);
}
}
//At the end of first iteration, swap pivot element with index2 element
strcpy(temp, array[pivotIndex]);
--> strcpy(array[pivotIndex], array[index2]);
strcpy(array[index2], temp);
//Recursive call for quick sort, with partiontioning
quicksort(array, firstIndex, index2-1);
quicksort(array, index2+1, lastIndex);
}
}
而我的main()
:
int main() {
int numStrings = 100, maxLen = 100;
char strings[numStrings][maxLen];
printf("Give me some strings, each on a new line, and write STOP to stop:\n");
char input[100];
scanf("%s", input);
int iteration = 0;
while (strcmp(input, "STOP") != 0) {
strcpy(strings[iteration], input);
iteration++;
scanf("%s", input);
}
quicksort(strings, 0, iteration);
int j;
printf("Your sorted strings:\n");
for (j = 0; j < iteration; j++) {
printf("%s\n", strings[j]);
}
return(0);
}
但是上面用箭头指示的线一直在给我SIGABRT错误。 上面我的代码有什么问题导致此? 我当然不熟悉C,所以如果对我的实现有什么灾难性的愚蠢,请这么说。
您正在调用quicksort(strings, 0, iteration);
它将尝试在可能存在内存访问冲突的iteration
位置访问元素。 对于iteration
大小的数组, iteration-1
是最后一个元素。 因此,您应该传递iteration-1
而不是iteration
。
另外,请检查迭代,因为它可能越界。
在strcpy(array[pivotIndex], array[index2]);
在quicksort
功能,pivotIndex和索引2可能是相同的,它可能会导致一些问题。 看到这个问题:strcpy(array [pivotIndex],array [index2]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.