下面的代码对大数组(大于400000个字,尽管我没有发现有限制)进行排序的单词数组进行排序。它被通过它传递的话数组(从文件中读取)进行排序,并测试其成功的一个项目叫做:C:仅适用于大文件的合并排序上的段错误
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "csort.h"
#include "sort.h"
// array points to array of pointers to strings, count is number of entries in array
void sortC(char** array, unsigned int count){
array = merge_sort(array, count);
// testing:
/*for (int i = 0; i < count; i++){
printf("%s ", array[i]);
}*/
}
char** merge_sort(char** array, int count){
if (count <= 1) return array;
else {
int lcount = 0;
int rcount = 0;
int middle = count/2;
lcount = middle;
char* left[lcount];
subArray(array, left, 0, middle);
rcount = count-middle;
char* right[rcount];
subArray(array, right, middle, count);
return merge(merge_sort(left, lcount), merge_sort(right, rcount), array, 0, lcount, rcount);
}
}
void subArray(char** array, char** subarray, int start, int end){
int ai; // index in original array
int si; // index in subarray
for (ai = start, si = 0; ai < end; ai++, si++){
subarray[si] = array[ai];
}
}
char** merge(char** left, char** right, char** output, int oi, int lcount, int rcount){
if (lcount > 0 && rcount > 0){
int lmin = findMinimum(left, lcount);
int rmin = findMinimum(right, rcount);
if (strcmp(left[lmin], right[rmin]) < 0){
output[oi] = left[lmin];
removeFromArray(left, lmin, lcount);
lcount--;
}
else {
output[oi] = right[rmin];
removeFromArray(right, rmin, rcount);
rcount--;
}
}
else if (lcount == 0) {
if (rcount == 1) {
output[oi] = right[0];
return output;
} else {
int rmin = findMinimum(right, rcount);
output[oi] = right[rmin];
removeFromArray(right, rmin, rcount);
rcount--;
}
}
else if (rcount == 0) {
if (lcount == 1) {
output[oi] = left[0];
return output;
} else {
int lmin = findMinimum(left, lcount);
output[oi] = left[lmin];
removeFromArray(left, lmin, lcount);
lcount--;
}
}
return merge(left, right, output, ++oi, lcount, rcount);
}
int findMinimum(char** array, int count){
char* minvalue = array[0];
char* currentvalue = minvalue;
int minindex = 0;
for (int i = 1; i < count; i++){
currentvalue = array[i];
if (strcmp(currentvalue, minvalue) < 0){
minvalue = currentvalue;
minindex = i;
}
}
return minindex;
}
void removeFromArray(char** array, int index, int count){
// removes specified index from an array
for (int i = index; i < count; i++){
if (i+1 == count){
array[i] = 0; // this entry will be gone when count decrements
} else {
array[i] = array[i+1];
}
}
}
这里有一个具体问题吗?你有没有在调试器中运行它以查看它在哪里进行分割? – 2011-04-21 17:11:42
(gdb)运行 输入文件名:kjvbible.txt 790691单词被读取。 编程接收到的信号SIGSEGV,分段故障。 0x08048a1d在合并中(左= 0xff518910,右= 0xff5006e0,输出= 0xff530bd0,oi = 35226,lcount = 7036,rcount = 7157)at csort.c:48 /home/elijah_houle/cs261/sort/csort.c:48 :1185:乞求:0x8048a1d – Elijah 2011-04-21 17:14:03
为什么它会出现故障?回溯没有帮助,因为它只显示“merge()”被称为数千次。 – Elijah 2011-04-21 17:15:26