Reputation:
This is an example of a c program to sort a list of names... I'm new to algorithms that's why I need to know what type it is! What are real life examples could I use it for too?
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main() {
char *str[5], *temp;
int i, j, n;
printf("\nHow many names do you want to have?");
scanf("%d", &n);
for (i = 0; i < n; i++) {
printf("\nEnter the name %d: ", i);
flushall();
gets(str[i]);
}
for (i = 0; i < n; i++) {
for (j = 0; j < n - 1; j++) {
if (strcmp(str[j], str[j + 1]) > 0) {
strcpy(temp, str[j]);
strcpy(str[j], str[j + 1]);
strcpy(str[j + 1], temp);
}
}
}
flushall();
printf("\nSorted List : ");
for (i = 0; i < n; i++)
puts(str[i]);
return (0);
}
Upvotes: 0
Views: 90
Reputation: 310940
First of all the program is invalid. It does not allocate memory where it is going to store strings. As result it is a very risky step to ask the user how many names does he want to have because there is no space to store strings in the program.:)
You could use a two-dimensional variable length character array for the strings and standard function fgets
instead of gets
to enter the strings.
As for the sort algorithm then it is a bad realization of the bubble sort.:)
Upvotes: 2
Reputation:
I hope its a bubble sorting. And with this you can arrange numbers in ascending or descending order.
Upvotes: 3