这是一个采用两个未排序数组 DTA 和 DTB 的程序。使用冒泡排序方法对它们进行排序,然后使用合并算法将两个数组合并为一个更大的数组 (big_array)。冒泡排序效果很好。然而我的合并算法使程序崩溃。该程序将运行冒泡排序部分,但当遇到合并部分时,它会崩溃。
任何建议都会很棒!
#include <stdio.h>
#include <string.h>
int main() {
//initialising variables and the arrays containing each of the four groups.
//
char *DTA [12] = { "James ", "John ", "Robert ", "Michael", "William ", "David ", "Richard ", "Joseph", "Thomas", "Charles", "Chris ", "Henry " };
char *DTB [14] = { "Brian ", "Edward", "Ronald ", "Tim ", "Jason ", "Jeff ", "Geoff ", "Ryan ", "Gary ", "Jacob ", "Nicholas", "Eric ", "Nicholas", "Larry " };
char *big_array [42];
int index = 0;
char temp[100];
int n = sizeof(DTA) / sizeof(DTA[0]);
int i = 0;
int j = 0;
int k = 0;
//This is a bubble sorting Algorithm. It sorts DTA & DTB in order and then prints the sorted arrays out.
//
for (int j = 0; j < n - 1; j++) {
for (int i = j + 1; i < n; i++) {
if (strcmp(DTA[j], DTA[i]) > 0) {
char *temp = DTA[j];
DTA[j] = DTA[i];
DTA[i] = temp;
}//end if
if (strcmp(DTB[j], DTB[i]) > 0) {
char *temp = DTB[j];
DTB[j] = DTB[i];
DTB[i] = temp;
}//end if
}//end for
}//end for
//This is a merging algorithm. It merges DTA & DTB into the array big_array.
//
while (index < 12 && j < 14) {
if (DTA[index] <= DTB[j]) {
big_array[k] = DTA[index];
index = index + 1;
}//end if
else
{
big_array[k] = DTB[j];
j = j + 1;
k = k + 1;
}//end else
}//end while
while (j < 14) {
big_array[k] = DTB[index];
index = index + 1;
k = k + i;
}//end while
for (int index = 0; index < n; index++)
printf("\n String %d is %s", index+1, big_array[i]);
getchar();
getchar();
return 0;
}//end main()
最佳答案
您在 DTA 移动时错过了 k
增量,在 DTB[j]
尾部复制中出错并忘记了 DTB[index]
复制:
while ( index < 12 && j < 14 )
{
if ( strcmp(DTA[index], DTB[j]) <=0 )
{
big_array[k] = DTA[index] ;
index = index + 1 ;
k = k + 1 ;
}//end if
else
{
big_array[k] = DTB[j] ;
j = j + 1 ;
k = k + 1 ;
}//end else
}//end while
while ( j < 14 )
{
big_array[k] = DTB[j] ;
j = j + 1 ;
k = k + 1 ;
}//end while
while ( index < 12 )
{
big_array[k] = DTA[index] ;
index = index + 1 ;
k = k + 1 ;
}//end while
for (int i=0; i<26; i++)
printf("\n String %d is %s", i+1, big_array[i]);
我还更正了 for-loop 的输出(看来你没有读你写的内容)
还要考虑使用常量/变量而不是魔法值
关于c - 在C中合并两个已排序的字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49831006/