I tried writing my own insertion sort
and swap
functions in C.
The insertion sort
or the swap
is compiling but not working yet.
input: gcc insertion.c -o insertion ./insertion alfalfa
Input: alfalfa
Output: 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;
}