我尝试用 C 编写自己的插入 sort
和 swap
函数。
插入 sort
或 swap
正在编译但尚未运行。
input: gcc insertion.c -o insertion ./insertion alfalfa
输入:紫花苜蓿
输出:紫花苜蓿
#include <stdio.h>
#include <string.h>
#define SORTL 20
char * insertionsort(int *countargs, char *word);
void swap(char *a, char *b);
/* Enter word to insertion sort at the terminal */
int main(int argc, char *argv[]){
/* Pass arguments from command line */
if(argc != 2)
perror("Please enter two arguments.");
int argcount = strlen(argv[1]);
char presort[SORTL];
strcpy(presort, argv[1]);
char * resultword;
resultword = insertionsort( &argcount, presort );
printf("Presort: %s\nPostsort: %s", presort, resultword);
return 0;
}
char * insertionsort(int *countargs, char word[]){
int i, j;
for( i = 1; i < *countargs; i++) {
j = i;
while( (j < 0) && (word[j] < word[j-1]) ) {
swap( &word[j], &word[j-1] );
j = j - 1;
}
}
return word;
}
void swap(char *a, char * b)
{
char temp;
temp = b;
b = a;
a = temp;
}
最佳答案
你需要改变swap函数
void swap(char *a, char * b)
{
char temp;
temp = *b;
*b = *a;
*a = temp;
}
因为,在 swap()
中,您需要交换内存中的字符,而不是变量指向的地址。
另一件事,通过最后的 printf()
语句,我觉得您想打印较旧的未排序字符串和较新的已排序字符串。如果是这样,那么它将不起作用。只会打印一个字符串,因为本质上你只是在交换初始字符串中的字符,而 resultword
指向同一个字符串,
resultword = insertionsort( &argcount, presort );
//sending presort and receiving it in word in the function insertionsort
//receiving the return in resultword
&
return word;
//and returning back the same address from insertionsort
编辑
while
循环中的条件不正确。应该是 j > 0
while( (j > 0) && (word[j] < word[j-1]) )
因为你是从远端开始,然后回到起点。
关于c - 在 C 中从命令行编写插入排序和交换函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33451506/