Having trouble with ascending insertion sort with strings in C -



Having trouble with ascending insertion sort with strings in C -

i having problem sorting out list of names in c. have code sorting names, when go print them out still in same order @ origin isnt right. function need help sort_data function. post of code can help guys out helping me! lot in advance, function has been killing me morning.

#include <string.h> #include <stdio.h> #include <stdlib.h> #define max_string_len 25 void insert_data(char **strings, const char* filename, int size); void allocate(char ***strings, int size); void sort_data(char **strings, int size); int main(int argc, char* argv[]){ if(argc != 4){ printf("wrong number of args"); } char **pointer; int size = atoi(argv[1]); allocate(&pointer, size); insert_data(pointer, argv[2], size); sort_data(pointer,size); } void sort_data(char **strings, int size){ int i, j; char temp[max_string_len]; for( = 1; < size; i++){ strcpy(temp, strings[i]); j = - 1; while( j >= 0 && strcmp(strings[i], temp) > 0) { strcpy(strings[j+1], strings[j]); j = j - 1; } strcpy(strings[j+1], temp); } int z; for(z = 0; z < size; z++){ printf("\n%s", strings[z]); } } void allocate(char ***strings, int size){ int i; *strings = malloc(sizeof(**strings) * size); for( = 0; < size; i++) { (*strings)[i] = malloc(sizeof(char) * max_string_len); } } void insert_data(char **strings, const char* filename, int size){ file *input; input = fopen(filename, "r"); int i; (i = 0; < size; i++){ fscanf(input,"%24s", strings[i]); } fclose(input); }

the list reading in follows:

matt susan mark david aden phil erik john caden mycah

so need list in alphabetical order, when run code , print out list after run sort function, still in order. alot 1 time 1 time again help.

what passing in 'size' here?

in sort_data(), seem utilize maximum string size:

char temp[size];

and number of strings in list:

for( = 1; < size; i++)

i don't know if problem, it's bound bite @ point.

eta: while loop needs work. notice in each iteration comparing 'strings[i]' 'temp', having set them equal each other before loop. nil within inner loop executed, , @ end of re-create 'temp' same location in 'strings'.

take few minutes map out needs happen each time run loop. run through on paper, , write downwards contents of array , values of 'i' , 'j'.

c string strcpy insertion-sort

Comments

Popular posts from this blog

php - Android app custom user registration and login with cookie using facebook sdk -

django - Access session in user model .save() -

php - .htaccess Multiple Rewrite Rules / Prioritizing -