sorting the names in alphabetical order without using string.h library  - Page 1
Forum section: electronics / general

author: Kittu20
author_rank: Regular Contributor
timestamp: January 01, 2023, 12:20:21 pm
content: Hey Guy'sI am trying to sort names in alphabetical order without using string.h library function. This is not the assignment I am solving this problem just for learning. I don't understand how to sort because each name has different lengthCode:#include<stdio.h>int main(){char Name = {"bob", "stev", "devid", "ratch", "king"};return 0;}Please give some ideas to solve the problem

author: tggzzz
author_rank: Super Contributor
timestamp: January 01, 2023, 12:37:52 pm
content: Based on this question andyour other question, you will benefit from understanding a general techinque:decide on some terminology that encapsulates your problemuse a search engine to find some answers, (probably ignoring stackexchange results since they are only useful for "which button do I press to floggle the thingumyjig" questions)if that doesn't help, readthisand then post a question on this forum or elsewhere.That will enable us to give you the best answers.

author: Ian.M
author_rank: Super Contributor
timestamp: January 01, 2023, 12:39:47 pm
content: Try googling: strcmp() implementation in CYou'll find lots of examples of how to write your own strcmp function.You may also need to write a toupper() or tolower() function so you can do a case independent alphabetic comparison.The NUL character at the end of the shorter string will always compare lower than the next character of the longer string so as long as your strcmp() terminates after comparing the NUL, not before, its easy to get the usual alphabetic sort order with the root string sorting ahead of strings extended from that root.You will also need write a sort function to reorder of the strings - the easiest solution there is to leave them where they are and build an array of pointers to them in the correct order. In fact, for consistency and ease of manipulation, its probably preferable to define the original string array as an array of pointers to strings. see:https://overiq.com/c-programming-101/array-of-pointers-to-strings-in-c/Then you have the choice as to whether to sort in-situ or by building a new array of pointers.

author: kripton2035
author_rank: Super Contributor
timestamp: January 01, 2023, 12:41:58 pm
content: ChatGPT answer to the question : "sorting the names in alphabetical order without using string.h library"Code:#include <stdio.h>#include <stdlib.h>#include <stdbool.h>#define MAX_NAMES 100char Name = {"bob", "stev", "devid", "ratch", "king"};void sort_names(char *names[], int n) {for (int i = 0; i < n; i++) {int min_index = i;for (int j = i + 1; j < n; j++) {if (strcmp(names, names) < 0) {min_index = j;}}if (min_index != i) {char *temp = names;names = names;names = temp;}}}int main(int argc, char **argv) {char *names;int n = 5;// Store the names in the names arrayfor (int i = 0; i < n; i++) {names = Name;}// Sort the namessort_names(names, n);// Print the sorted list of namesprintf("\nSorted list of names:\n");for (int i = 0; i < n; i++) {printf("%s\n", names);}return 0;}

author: Ian.M
author_rank: Super Contributor
timestamp: January 01, 2023, 12:47:29 pm
content: And where's the learning in that?

author: tggzzz
author_rank: Super Contributor
timestamp: January 01, 2023, 12:57:37 pm
content: Quote from: Ian.M on January 01, 2023, 12:47:29 pmLearns about the existance of another tool, how to use it, and hopefully why it is necessary to critically evaluate answers

author: SiliconWizard
author_rank: Super Contributor
timestamp: January 01, 2023, 07:44:15 pm
content: Quote from: tggzzz on January 01, 2023, 12:57:37 pmIndeed.

author: Nominal Animal
author_rank: Super Contributor
timestamp: January 02, 2023, 06:22:12 am
content: Quote from: Kittu20 on January 01, 2023, 12:20:21 pmYou need two things: a string compare function (likestrcmp()), and a sort function (likeqsort()).The string compare function compares two input strings character by character. If the first string sorts before the second one, the function returns negative. If the first string sorts after the second one, the function returns positive. If the strings are equal, the function returns 0.The function does this using a single loop, first iteration comparing first characters, and so on, until either the characters differ, or one or both strings end.If you useqsort()from<stdlib.h>, the man page includes an example.

author: westfw
author_rank: Super Contributor
timestamp: January 09, 2023, 01:20:11 am
content: QuoteChatGPT gets an F. strcmp() is part of string.hTo handle strings of non-matching length, you have todecidewhether "bob" comes before or after "bobby." After that, it's easy:Code:if (endOfString(s1))if (!endOfString(s2))return S1ISLESS; // or S1ISGREATER

author: mfro
author_rank: Regular Contributor
timestamp: January 09, 2023, 12:58:46 pm
content: Quote from: westfw on January 09, 2023, 01:20:11 amif you decide the shorter string to be the lexicographic "smaller" one (which is kind of obvious), you can simplify your program by considering the trailing '\0' as part of the string.

author: Nominal Animal
author_rank: Super Contributor
timestamp: January 09, 2023, 02:21:50 pm
content: A common way to implement it on systems with ASCII-compatible character sets (including UTF-8) is to loop until the characters differ, or they are nuls. Then, the return value is((unsigned char)(character_in_s1) - (unsigned char)(character_in_s2)).Aw crap, here you go:Code:// For qsort() on arrays of strings (arrays of pointers to char or unsigned char)int compare(const void **p1, const void **p2){const unsigned char *const s1 = *(const unsigned char **)p1;const unsigned char *const s2 = *(const unsigned char **)p2;size_t i = 0;while (s1 == s2 && s1 != '\0') {i++;}return (s1) - (s2);}or, for a case-insensitive comparison that considers all whitespace equal and considers decimal numbers by value, usingtolower()andisspace()andisdigit()from<ctype.h>(use<locale.h>andsetlocale(LC_ALL, "")to make it use your locale at run time):Code:// For qsort() on arrays of strings (arrays of pointers to char or unsigned char)int humancompare(const void **p1, const void **p2){const unsigned char *s1 = *(const unsigned char **)p1;const unsigned char *s2 = *(const unsigned char **)p2;while (1) {unsigned char c1 = *(s1++);unsigned char c2 = *(s2++);if (isdigit(c1) && isdigit(c2)) {const unsigned char *end1 = s1;const unsigned char *end2 = s2;// Skip to end of decimal number in s1while (isdigit(*end1))end1++;// Skip to end of decimal number in s2while (isdigit(*end2))end2++;// Digit offsetsize_t i = 0;// Maximum number of digits to examineconst size_t n1 = (size_t)(end1 - s1);const size_t n2 = (size_t)(end2 - s2);// is the smaller of the twoconst size_t n = (n1 < n2) ? n1 : n2;// Compare decimal numbers from right to leftwhile (i < n) {const int d = end1[-i] - end2[-i];if (d)return d; // Digits differelsei++;}if (i < n1) {// First string was shorterreturn -1;} elseif (i < n2) {// Second string was shorterreturn +1;} else {// Decimal numbers match, continue after thems1 = end1;s2 = end2;continue;}}if (isspace(c1)) {// Consider all consecutive whitespace equivalent to a single spacewhile (isspace(*s1))s1++;c1 = ' ';} else {// Convert to lower casec1 = tolower(c1);}if (isspace(c2)) {// Consider all consecutive whitespace equivalent to a single spacewhile (isspace(*s2))s2++;c2 = ' ';} else {// Convert to lower casec2 = tolower(c2);}// We have a result if the characters differ or both strings end.if (c1 != c2 || c1 == '\0')return c1 - c2;}}For human text, you'd need to use wide character strings andiswspace(),iswdigit(), andtowctrans()(with desc=wctrans("tolower")and desc=wctrans("toupper), since not all letters in all languages have both lower- and uppercase versions).The conversion between "normal" multibyte strings and wide strings is done using for examplembstowcs()andwcstombs().This way, if you localize your program properly usingsetlocale(LC_ALL, "")(or for character set and types only usingsetlocale(LC_CTYPE, "")), you can sort in human-preferred order in whatever locale the user has set.

author: Sherlock Holmes
author_rank: Frequent Contributor
timestamp: January 10, 2023, 04:29:49 pm
content: Did the original poster ever bother to return and read people's answers?