2015-10-31 33 views
1

交换功能我试着写我自己的插入sortswap功能C. 插入sortswap正在编制,但还没有成型。写作插入排序,并在命令行中使用C

输入:GCC insertion.c -o插入./insertion苜蓿

输入:苜蓿

输出:苜蓿

#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; 
} 

回答

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

既然你是从远端开始,并开始。

+0

谢谢,我试着编译如上,它仍然输出未排序的词 –

+0

你的冠军,j从来没有大于零,我把它切换到(j <0),它的工作原理! –

+0

@JulianWise“* ..永远不会少于零*”。谢谢 :) – Haris

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

+0

谢谢,我试着按上面的方法编译,输出仍然失败 –

+0

因为他正在检查'word [j-1]',所以不应该是'j> = 0'。这也会导致'word [-1]'。 – Haris

+0

@Haris忽略了这一点,谢谢! :) – ameyCU