交换功能我试着写我自己的插入sort
和swap
功能C. 插入sort
或swap
正在编制,但还没有成型。写作插入排序,并在命令行中使用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;
}
谢谢,我试着编译如上,它仍然输出未排序的词 –
你的冠军,j从来没有大于零,我把它切换到(j <0),它的工作原理! –
@JulianWise“* ..永远不会少于零*”。谢谢 :) – Haris