C Selection Sort 🎯

beginner
8 min

C Selection Sort 🎯

Welcome to our deep dive into the world of C Programming! Today, we're going to learn about one of the simplest sorting algorithms: Selection Sort. By the end of this lesson, you'll have a solid understanding of this essential algorithm and how to implement it in your own C programs. 📝

What is Selection Sort? 📝

Selection Sort is a simple sorting algorithm that works by repeatedly finding the minimum element from the unsorted part of the array and putting it in the correct position in the sorted part.

Let's break it down:

  1. Find the minimum element in the unsorted array and place it at the beginning of the sorted array.
  2. Find the second minimum element and place it next to the first one.
  3. Repeat this process until the entire array is sorted.

Why Use Selection Sort? 💡

Selection Sort is a simple algorithm and easy to understand, making it a great choice for beginners. It's also in-place, meaning it doesn't require additional memory to sort an array. However, it's not the most efficient algorithm for large data sets due to its quadratic time complexity.

Implementing Selection Sort in C 💻

Now, let's write some code! Here's a simple implementation of Selection Sort in C:

c
#include <stdio.h> void selectionSort(int arr[], int n) { for (int i = 0; i < n - 1; i++) { int minIndex = i; // Find the minimum element in unsorted array for (int j = i + 1; j < n; j++) if (arr[j] < arr[minIndex]) minIndex = j; // Swap the found minimum element with the first element int temp = arr[minIndex]; arr[minIndex] = arr[i]; arr[i] = temp; } } void printArray(int arr[], int size) { for (int i = 0; i < size; i++) printf("%d ", arr[i]); printf("\n"); } int main() { int arr[] = {64, 25, 12, 22, 11}; int n = sizeof(arr) / sizeof(arr[0]); printf("Unsorted array: \n"); printArray(arr, n); selectionSort(arr, n); printf("Sorted array: \n"); printArray(arr, n); return 0; }

In this code, we first define a function selectionSort to sort the array. We then create an arr array, initialize it with some values, and print both the unsorted and sorted arrays.

Quiz Time 📝

Quick Quiz
Question 1 of 1

Which of the following statements correctly describes the time complexity of Selection Sort?

That's it for today! You now have a basic understanding of the Selection Sort algorithm and how to implement it in C.

In the next lesson, we'll dive deeper into C programming, exploring more algorithms and techniques to help you become a master of this versatile language. Happy coding! 🚀