Algorithm for Selection Sort in C with Example

Algorithm for Selection Sort in C

The simplest and most effective algorithm for many applications, ranging from database data organization to search optimization on websites, has to be Selection Sort. Let’s dive deep into how it works, along with manually step-by-step examples, discussing complexities, advantages, disadvantages, real-world applications, and algorithm for selection sort in C. Let’s get started right away.

What is the Selection Sort?

Selection sort is one of the simplest algorithms. How can it be described? At each step, the smallest (or largest) element in the unsorted portion of the array is identified and swapped with the first unsorted element. This process is repeated until the entire array is sorted.

The algorithm divides the list into two parts:

  1. Sorted part (initially empty).
  2. Unsorted part (contains the entire list at the start).

Working of Selection Sort

Follow these steps:

  1. Start with the first element in the list.
  2. Find the smallest (or largest) element in the unsorted part of the list.
  3. Swap it with the first element of the unsorted part.
  4. Move the boundary between the sorted and unsorted parts to the right.
  5. Repeat until the list is completely sorted.

Algorithm for Selection Sort in C Code:

#include <stdio.h>

// Function to perform Selection Sort
void selectionSort(int arr[], int n) {
    int i, j, min_idx, temp;

    // Move the boundary between sorted and unsorted parts
    for (i = 0; i < n-1; i++) {
        // Find the minimum element in unsorted array
        min_idx = i;
        for (j = i+1; j < n; j++) {
            if (arr[j] < arr[min_idx]) {
                min_idx = j;
            }
        }

        // Swap the found minimum element with the first element
        temp = arr[min_idx];
        arr[min_idx] = arr[i];
        arr[i] = temp;
    }
}

// Function to print the array
void printArray(int arr[], int n) {
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");
}

int main() {
    int arr[] = {64, 25, 12, 22, 11};
    int n = sizeof(arr)/sizeof(arr[0]);

    selectionSort(arr, n);
    printf("Sorted array: \n");
    printArray(arr, n);
    
    return 0;
}

Output:

Sorted array: 
11 12 22 25 64

Manual Steps of Algorithm for Selection Sort

Let’s manually step through the algorithm with the array [64, 25, 12, 22, 11].

  • Step 1:
    • Unsorted: [64, 25, 12, 22, 11]
    • Find the smallest element: 11
    • Swap 11 with the first element: [11, 25, 12, 22, 64]
  • Step 2:
    • Unsorted: [25, 12, 22, 64]
    • Find the smallest element: 12
    • Swap 12 with the second element: [11, 12, 25, 22, 64]
  • Step 3:
    • Unsorted: [25, 22, 64]
    • Find the smallest element: 22
    • Swap 22 with the third element: [11, 12, 22, 25, 64]
  • Step 4:
    • Unsorted: [25, 64]
    • Find the smallest element: 25
    • No swap is needed (it’s already in the right place).

The array is now sorted: [11, 12, 22, 25, 64].


Time Complexity

The time complexity of the selection sort is O(n²), where n is the number of elements in the list.

  • Best case: O(n²) – Even if the list is already sorted, it still performs all the comparisons.
  • Average case: O(n²) – In most random scenarios, it performs the same number of operations.
  • Worst case: O(n²) – The worst happens when the list is in reverse order.

Space Complexity

Selection sort has a space complexity of O(1) since it operates in place, meaning it requires no additional storage except for a few variables.


Advantages

  • Simplicity: The algorithm is easy to understand and implement, making it a great choice for educational purposes.
  • In-Place Sorting: It doesn’t require extra memory beyond what’s already needed for the input array, which can be useful in memory-constrained environments.
  • Performs Well on Small Lists: For smaller datasets, the algorithm can be quite efficient and doesn’t carry much overhead.

Disadvantages

  • Inefficient for Large Data: The algorithm’s O(n²) time complexity makes it impractical for large datasets, where more efficient algorithms (like quicksort or mergesort) should be used.
  • No Adaptability: It doesn’t adapt to already-sorted arrays or partially sorted arrays—it performs the same number of comparisons regardless.
  • Unstable: It’s an unstable sort, meaning that if two elements have the same value, their relative order in the original list may not be preserved in the sorted list.

Applications of Selection Sort

Although it is not typically used in production environments due to its inefficiency, it does have certain niche applications:

  • Small Data Sets: Selection sort can be useful for sorting small arrays where its simplicity and in-place sorting are advantages.
  • Embedded Systems: In some embedded systems with limited resources, where memory is constrained but speed is less of a concern, selection sort may still be an option.
  • Didactic Purposes: Due to its simplicity, it is widely taught as an introductory sorting algorithm in computer science courses, helping students understand the concept of sorting and algorithm efficiency.

Frameworks, Libraries, and Technologies Using Selection Sort

While selection sort is not commonly used in high-performance applications due to its inefficiency for larger datasets, it can still be found in various educational tools and simple implementations. Here’s a look at some frameworks, libraries, and technologies where it might be used:

Game Development

In game development, it can sometimes be used for simple sorting tasks, particularly when performance is not a critical factor. Examples include:

  • Unity: While Unity itself may not use it directly, developers might use it in smaller scripts for sorting game elements, like arranging items in an inventory or sorting leaderboard scores.
Algorithm for Selection Sort in Games

Embedded Systems

It can also find its way into embedded systems programming, where memory and processing power are limited:

  • Arduino Projects: Simple sorting of small datasets in Arduino projects might use selection sort for its straightforward implementation, especially when the sorting task is minimal.

GUI Applications

In some graphical user interface applications, it might be utilized for small lists:

  • Small-scale Desktop Applications: Applications like personal finance managers or note-taking apps with limited data entries could implement selection sort to manage or sort their internal data.

Why Use Selection Sort When Faster Algorithms Exist?

You might wonder, “If more efficient algorithms exist, why even consider selection sort?” That’s a valid point! In most real-world scenarios, algorithms like quick sort or merge sort outperform selection sort by a mile. However, when we’re dealing with tiny datasets (say, less than 10 elements), the selection sort’s overhead is minimal, and its simpler operations can be executed quickly. Plus, if you’re ever coding for microcontrollers or basic systems where memory is limited, space complexity becomes the deciding factor, and that’s where it wins.


Selection Sort Algorithm in the Real World

Sure, selection sort isn’t the go-to algorithm when your online store’s recommendation engine needs to process millions of customer records daily. But imagine you’re building an interactive educational app. Here, teaching children or beginners the fundamental logic of sorting numbers might benefit from this simple, clear-cut approach. It could power a fun, visual demonstration where users drag and drop elements while the app slowly sorts the data in the background, illustrating each step visually. It’s all about context.


Final Thoughts

Selection sort, though not the fastest or most efficient algorithm, is valuable for teaching and certain specialized systems where simplicity and low memory usage are critical. It’s the kind of algorithm that, despite its disadvantages, continues to resurface in specific situations and serves as a stepping stone toward mastering more sophisticated sorting techniques. If you’d like to practice implementing Selection Sort or test your skills with other algorithms, check out the HackerRank Algorithms Practice section, where you can solve real-world problems and improve your coding abilities.

What do you think? Would you use selection sort in your next project, or is it best left in textbooks?

Scroll to Top