c - 在 C 中从命令行编写插入排序和交换函数

标签 c command-line-arguments swap insertion-sort insertion

我尝试用 C 编写自己的插入 sortswap 函数。 插入 sortswap 正在编译但尚未运行。

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/

相关文章:

tcl - 出现错误时从命令行退出 Modelsim

c - 我如何使用 getopt_long 处理 c 中的参数

c++ - C++ 的更好的 ow level int 交换

c++ - C语言中函数中的switch指针

c - 动态数组分配和复制到更大的

c - C语言的“随机长度”?

c - MD5——添加消息长度

c - 在c中为两个不同的数组分配相同的下标

python - 在Python中解析独占组

string - 如何在golang中交换字符串的子字符串?