24.10.25

12. Insertion Sort (Strings), The One Where Friends Alphabetize Like Card Players

  

hello everyone 

After sorting numbers with Insertion Sort, Aarav said, “That was easy I’m basically a human sorting machine now!” Riya rolled her eyes (as usual ) and said, “Cool, then let’s see you sort words instead of numbers!” That’s when we jumped into Insertion Sort for strings and wow, it was like playing cards but with words!

What’s Happening Here?

You start by entering a bunch of words. Then, the program takes one word at a time and inserts it into its correct position among the already sorted ones just like arranging cards in your hand in alphabetical order (except no cheating this time, Aarav ). Each step builds a perfectly sorted list from A to Z neat, simple, and super beginner-friendly!

How It Works?

Riya was our sorting champ again carefully inserting each word into place like she’s organizing a dictionary. Aarav helped too, though he once placed “zebra” before “apple” and proudly said, “Close enough!” And I (Daksh) handled the printing part, pretending I did most of the work .

Code:

 #define _CRT_SECURE_NO_WARNINGS
 #include <stdio.h>
 #include <string.h>
 
 int main() {
     char words[100][50];       // Array to store strings
     char currentWord[50];      // Current word for insertion
     int totalWords;            // Total number of words
     int index, previousIndex;  // Loop counters
     char continueChoice[10];   // To store user's choice to continue (yes/no)
 
     do {
         printf("Enter number of words (max 100): ");
         scanf("%d", &totalWords);
 
         printf("Enter %d word(s):\n", totalWords);
         for (index = 0; index < totalWords; index++) {
             scanf("%s", words[index]);
         }
 
         // Insertion sort
         for (index = 1; index < totalWords; index++) {
             strcpy(currentWord, words[index]);
             previousIndex = index - 1;
             while (previousIndex >= 0 && strcmp(words[previousIndex], currentWord) > 0) {
                 strcpy(words[previousIndex + 1], words[previousIndex]);
                 previousIndex--;
             }
             strcpy(words[previousIndex + 1], currentWord);
         }
 
         printf("\nWords in alphabetical order:\n");
         for (index = 0; index < totalWords; index++) {
             printf("%d. %s\n", index + 1, words[index]);
         }
 
         printf("\nDo you want to sort another set of words? (yes/no): ");
         scanf_s("%s", continueChoice, (unsigned)sizeof(continueChoice));
 
     } while (strcmp(continueChoice, "yes") == 0 || strcmp(continueChoice, "YES") == 0);
 
     printf("\nOkay, exiting the program.\n");
     return 0;
 }


Output:

  

← Previous 🏠 Homepage Next Chapter →

No comments:

Post a Comment

rating System

Loading...

A Friendship Story of Learning Data Structures with C

Sr. No. DSU BLOGS CHAPTERS 1 Array Operations in C, The Group of Friendship (Create, Insert, Delete ...