1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
|
// Uses bubble sort to sort an array into
// non-descending order. (Non-descending order is basically
// ascending order but allows duplicates).
#include <stdio.h>
#include <string.h>
#define MAXELEMENTS 10
#define MAXSTRING 20
void readArray(char string[][MAXSTRING], int size);
void sortArray(char string[][MAXSTRING], int size);
void printArray(char string[][MAXSTRING], int size);
int main(int argc, char * argv[]){
char text[MAXELEMENTS][MAXSTRING];
printf("Please enter %d strings:\n",MAXELEMENTS);
readArray(text,MAXELEMENTS);
sortArray(text,MAXELEMENTS);
printf("The sorted array:\n");
printArray(text,MAXELEMENTS);
return 0;
}
//Reads in exactly size numbers into the given array
void readArray(char string[][MAXSTRING],int size){
int i;
for(i=0; i < size; i++){
fgets(string, MAXSTRING, stdin);
}
}
// This function sorts the given array using bubble sort
void sortArray(char string[][MAXSTRING], int size){
int i;
char swap[MAXSTRING];
int unsortedLen=size, swapped=1;
//If we went through the whole for loop without swapping
//the array is in order and we can stop sorting
while ( swapped ) {
swapped=0;
//We go only up to unsortedLen -1
//otherwise
for ( i =0; i < unsortedLen -1 ; i++){
if ( string[i] > string[i+1] ){
strcpy(swap, string[i]);
strcpy(string[i], string[i+1]) ;
strcpy(string[i+1], swap);
swapped=1;
}
}
unsortedLen = unsortedLen - 1;
}
}
//Prints an array of integers of a given size
void printArray(char string[][MAXSTRING], int size){
int i;
//Print out the array
for(i=0;i< size; i++){
printf("%s\n",string[i]);
}
}
|