#include <stdio.h> #include <string.h> //*** Sorts an array of strings in place
ID: 3923983 • Letter: #
Question
#include <stdio.h> #include <string.h>
//*** Sorts an array of strings in place ***// // // Inputs: // strings: the array of strings, each entry is type char * // length: the number of entries in the array // // Returns: nothing, the strings are sorted in place void stringSort(char *strings[], int length) { // Write code to sort strings using any sorting algorithm return; }
int main() { char *animals[] = {"zebra", "quail", "xenops", "aardwolf", "aardvark", "dog", "bear", "cat", "bearcat"}; stringSort(animals, 9); int i; for (i = 0; i < 9; i++) { printf("%s ", animals[i]); }
return 0; }
Explanation / Answer
#include <stdio.h>
#include <string.h>
//*** Sorts an array of strings in place ***//
//
// Inputs:
// strings: the array of strings, each entry is type char *
// length: the number of entries in the array
//
// Returns: nothing, the strings are sorted in place
void stringSort(char *strings[], int length) {
// Write code to sort strings using any sorting algorithm
int i, j;
for(i = 0; i < length - 1; i++){
j = i;
while(j > 0 && strcmp(strings[j - 1], strings[j]) > 0){
char *temp = strings[j - 1];
strings[j - 1] = strings[j];
strings[j] = temp;
j--;
}
}
}
int main() {
char *animals[] = {"zebra", "quail", "xenops",
"aardwolf", "aardvark", "dog",
"bear", "cat", "bearcat"};
stringSort(animals, 9);
int i;
for (i = 0; i < 9; i++) {
printf("%s ", animals[i]);
}
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.