hello everyone
After we nailed Selection Sort, Aarav proudly said, “Now I can sort anything!”
But Rahul laughed and replied, “Really? Let’s see you handle it when the numbers come one by one like cards in a hand!” And that’s how we ended up learning Insertion Sort — the “card player” of sorting algorithms!
What’s new here?
Insertion Sort doesn’t just swap things around randomly it works smoothly. Imagine you’re holding cards each time you pick a new one, you slide it into its proper spot among the cards you already have. That’s exactly how this algorithm works! You can even choose to enter one number at a time or a bunch of them together and it’ll sort them all neatly. It’s simple, logical, and perfect for beginners.
How It Works ?
Rahul, as usual, took the lead inserting each number perfectly into its position like a sorting king. Aarav tried to help but kept saying, “Wait, where does this one go again?”
Meanwhile, I (Daksh) displayed the sorted results and pretended to be the “team leader” just because I had the print statements .
Meanwhile, I (Daksh) displayed the sorted results and pretended to be the “team leader” just because I had the print statements .
Code:
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <string.h> int main() { int numbers[100]; // Array to store numbers int totalNumbers; // Total number of numbers int index, previousIndex, currentNumber; // Loop counters and current number char continueChoice[10]; // Store user's choice to continue (yes/no) char elementChoice[10]; // single or multiple numbers do { printf("Do you want to enter 'single' or 'multiple' numbers? "); scanf("%s", elementChoice); if (strcmp(elementChoice, "single") == 0) { totalNumbers = 1; } else { printf("Enter number of elements (max 100): "); scanf("%d", &totalNumbers); } printf("Enter %d number(s):\n", totalNumbers); for (index = 0; index < totalNumbers; index++) { scanf("%d", &numbers[index]); } // Insertion sort for (index = 1; index < totalNumbers; index++) { currentNumber = numbers[index]; previousIndex = index - 1; while (previousIndex >= 0 && numbers[previousIndex] > currentNumber) { numbers[previousIndex + 1] = numbers[previousIndex]; previousIndex--; } numbers[previousIndex + 1] = currentNumber; } printf("\nNumbers in sorted order:\n"); for (index = 0; index < totalNumbers; index++) { printf("%d. %d\n", index + 1, numbers[index]); } // Ask if user wants to continue printf("\nDo you want to sort another set of numbers? (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