I have a C program that takes an array of strings, sorts using selection sort, and also searches a string in the sorted list. The selection sort doesn't work.
The code to display the string is OK. I also tried to verify if the smallest string is identified and yes it does. But it is not moved in its correct position as the selection sort should work. In the main function after displaying the unsorted strings, the program terminates. Where am I not doing the right thing?
Here is the code for the entire program:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void doDisplay(char *council[15], int size) {
int i;
for (i = 0; i < 15; i++) {
//printf("\n%s", council[i]);
puts(council[i]);
}
}
void select(char *council[15], int size) {
int pass, i, smallest;
char temp[];
for (pass = 0; pass < size; pass++) {
smallest = pass;
for (i = pass + 1; i < size; i++) {
if (strcmp(council[i], council[i - 1]) < 0) {
smallest = i;
}
}
printf("Value of smallest is: %d\n", smallest);
if (smallest != pass) {
strcpy(temp, council[pass]);
strcpy(council[pass], council[smallest]);
strcpy(council[smallest], temp);
}
}
}
int BinSearch(char *council[15], char *name, int min, int max) {
int mid;
min = 0;
max = 15;
while (min < max) {
int mid = (min + max) / 2;
if (strcmp(council[mid], name) == 0) {
printf("%s", name);
return 1;
} else
if (strcmp(council[mid], name) > 1) {
max = mid - 1;
BinSearch(council, name, min, max);
} else {
min = mid + 1;
BinSearch(council, name, min, max);
}
}
}
int main() {
int result = 0;
char *key;
char *council[15] = {
"Bert", "Jeff", "Gary", "Neba", "Chang",
"Olga", "Nora", "Mary", "Vera", "Rani",
"Neil", "Jill", "Cain", "Lara", "Bart"
};
printf("Before Sorting\n");
doDisplay(council, 15);
select(council, 15);
printf("\nAfter Sorting");
doDisplay(council, 15);
printf("Enter search key: ");
gets(key);
scanf("%s", &key);
result = BinSearch(council, &key, 0, 15);
return 0;
}