Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* Example: bubble sort strings in array */
- #include <stdio.h> /* Need for standard I/O functions */
- #include <string.h> /* Need for string functions */
- #include <stdlib.h>
- #define NUM 25 /* number of strings */
- #define LEN 1000 /* max length of each string */
- int main()
- {
- char* Strings[NUM];
- char temp[LEN];
- int length;
- printf("Please enter %d strings, one per line:\n", NUM);
- /* Write a for loop here to read NUM strings, using fgets(). */
- for (int i=0; i < NUM; i++) {
- /* Read one line of input into a temp string that is long enough (LEN long) */
- fgets(temp, LEN, stdin);
- length = strlen(temp - 1);
- /* Allocate memory space for String[i] that is only large enough to copy the
- string just read into it. Suppose the length of the string read into
- temp is "length", then you can use the following: */
- Strings[i] = malloc(length+1); /* Plus one for the NULL at end */
- strcpy(*(Strings + i), temp);
- }
- puts("\nHere are the strings in the order you entered:");
- /* Write a for loop here to print all the strings. */
- for(int l = 0; l < NUM; l++)
- {
- printf("%s", Strings[l]);
- }
- for(int o = 0; o < NUM; o++)
- {
- for(int y = 0; y < NUM - 1; y++)
- {
- if(strcmp(Strings[y], Strings[y+1]) > 0)
- {
- int length = strlen(Strings[y+1]);
- char temp[1][length];
- //swap function
- temp[0] = *Strings[y+1];
- *Strings[y+1] = *Strings[y];
- *Strings[y] = temp[0];
- }
- }
- }
- /* Output sorted list */
- puts("\nIn alphabetical order, the strings are:");
- /* Write a for loop here to print all the strings. */
- /* Write a loop here to use free() to free up space allocated
- for all of the strings above. */
- for(int p = 0; p < NUM; p++)
- {
- printf("%s", Strings[p]);
- free(Strings[p]);
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement