Mega Code Archive

 
Categories / C / Code Snippets
 

Function Sort string

#include <stdio.h> #include <stdlib.h> #include <string.h> #define TRUE 1 #define FALSE 0 void str_sort(char *[], int); void str_out(char *[], int); #define BUFFER_LEN 240 #define NUM_P 50 int main() { char *pS[NUM_P]; int count = 3; int j = 0; /* Loop counter */ pS[0] = "x1"; pS[1] = "x2"; pS[2] = "x3"; str_sort( pS, count ); printf("\nYour input sorted in order is:\n\n"); for (j = 0 ; j<count ; j++) { printf("%s\n", pS[j]); /* Display a string */ free(pS[j]); /* Free memory for the string */ pS[j] = NULL; } } void str_sort(char *p[], int n) { char *pTemp = NULL; int j = 0; int sorted = FALSE; while(!sorted) { sorted = TRUE; for( j = 0 ; j<n-1 ; j++ ) if(strcmp(p[j], p[j + 1]) > 0) { sorted = FALSE; pTemp= p[j]; p[j] = p[j + 1]; p[j + 1] = pTemp; } } }