hello everyone
So after mastering Bubble Sort, Aarav proudly said, “That’s it sorting is easy!”
But Rahul smirked (again ) and said, “Try doing it without swapping neighbors all the time.”
That’s how we ended up learning Selection Sort a cleaner and smarter way to sort numbers!
What’s New Here?
This one works a little differently. Instead of swapping neighbors all the time, it finds the smallest number in the list and puts it in the right spot. Then it moves to the next position, finds the next smallest number, and places it correctly and so on. It’s pretty neat, and it even lets you sort multiple sets of numbers. You can literally see how the algorithm picks out the right number each time. Aarav said it’s like picking the smallest candy first from a jar , and honestly… that’s not a bad comparison
How It Works
-
Rahul handled finding the smallest elements he’s fast like that.
-
Aarav did all the swapping, even though he still confused indexes .
-
I (Daksh) just kept printing the sorted arrays like a proud coder.
Code:
#include <stdio.h> #include <string.h> int main() { int numbers[100]; // Array to store numbers int totalElements; // Number of elements in the array int index, pass, minIndex; // Loop counters and index of minimum element int temporaryValue; // Used for swapping values char choice[10]; // To store user choice (yes/no) do { // Input number of elements printf("Enter the number of elements: "); scanf_s("%d", &totalElements); // Input elements printf("Enter %d numbers:\n", totalElements); for (index = 0; index < totalElements; index++) { scanf_s("%d", &numbers[index]); } // Selection Sort logic for (pass = 0; pass < totalElements - 1; pass++) { minIndex = pass; // Assume first element of unsorted part is minimum for (index = pass + 1; index < totalElements; index++) { if (numbers[index] < numbers[minIndex]) { minIndex = index; // Update minIndex if smaller element found } } // Swap the found minimum with the first element of unsorted part temporaryValue = numbers[pass]; numbers[pass] = numbers[minIndex]; numbers[minIndex] = temporaryValue; } // Display sorted array printf("\nSorted Array in Ascending Order:\n"); for (index = 0; index < totalElements; index++) { printf("%d ", numbers[index]); } printf("\n"); // Ask if user wants to continue printf("\nDo you want to sort another set of numbers? (yes/no): "); scanf_s("%s", choice, (unsigned)sizeof(choice)); } while (strcmp(choice, "yes") == 0 || strcmp(choice, "YES") == 0); printf("\nOkay, exiting the Selection Sort program.\n"); return 0; }
Output:
| ← Previous | 🏠 Homepage | Next Chapter → |
No comments:
Post a Comment