在C中从命令行编写插入排序和交换功能

时间:2015-10-31 12:20:51

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

我尝试在C中编写自己的插入sortswap函数。 插入sortswap正在编译但尚未正常工作。

  

输入: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;   
}

2 个答案:

答案 0 :(得分:3)

您需要更改交换功能

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]) )

因为你从远端开始并开始。

答案 1 :(得分:1)

1。在此功能中 -

void swap(char *a, char * b)
{ 
   char temp;            
   temp = b;             //assigining char * to char 
   b   = a;
   a   = temp;           // same here 
}

abchar *,取消引用指针ab然后交换 -

void swap(char *a, char * b)
{
   char temp;
   temp = *b;
   *b   = *a;
   *a   = temp;   
}

2。在你的功能中 -

for( i = 1; i < *countargs; i++) {
    j = i;
    while( (j < 0) && (word[j] < word[j-1])){   //this loop will not works as j is not < 0
        swap( &word[j], &word[j-1] );
        j = j - 1;
    }
}

while开始,j循环不会迭代,因为0不小于while,因此不会检查第二个条件。在j<0圈内,此条件j>0应为PC <- read.csv("protein_coding.csv") age <- read.table("Annotations_SubjectPhenotypes_DS.txt")