Home » C/C++ Data Structure programs

# C program to implement Selection Sort Algorithm

**Selection Sort Algorithm**: Here, we are going to learn about the selection sort algorithm, how it works, and C language implementation of the selection sort.

Submitted by Sneha Dujaniya, on June 19, 2020

**Selection sort** is an unstable, in-place sorting algorithm. The standard implementation is unstable but it can be made stable with a few modifications.

- A
**stable sorting algorithm**is the one where two keys having equal values appear in the same order in the sorted output array as it is present in the input unsorted array. - An
**in-place sorting algorithm**has various definitions but a more used one is - An in-place sorting algorithm does not need extra space and uses the constant memory for manipulation of the input in-place. Although, it may require some extra constant space allowed for variables.

It is an effective sorting algorithm with the worst time complexity of **O(N^2)** where *N* is the total number of elements. **Selection sort** functions by iteratively finding the smallest element and placing it at the start of the list. Thus, at the end of each iteration, the smallest element is placed at its current position in the sorted array.

**Algorithm:**

The algorithm maintains two sub-arrays. One sorted sub-array and another unsorted sub-array.

- Find the smallest element in the unsorted array.
- Swap this element with the element at the front of the whole array thus shifting the first smallest element to its correct position in the sorted array
- Repeat steps 1 - 2 for the next
*n-1*elements.

**Pseudo-code:**

1. for i <- 1 to n-1 2. i <- smallest 3. for j <- i+1 to n 4. if array[j] < array[smallest] 5. smallest <- j 6. End if 7. End for 8. Swap array[i] and array[smallest] 9. End for

**Example:**

**Input Array: **12 5 8 13

**Iteration 1:**

Minimum element in arr[0 - 3]: 5, shift it to the start of arr[0 - 3]

Array:** 5 **12 8 13

**Iteration 2:**

Minimum element in arr[1 - 3]: 8, shift it to the start of arr[1 - 3]

Array:** 5 8** 12 13

**Iteration 3:**

Minimum element in arr[2 - 3]: 12, shift it to the start of arr[2 - 3]

Array:** 5 8** **12** 13

Last element gets sorted automatically.

**Time Complexity: **The time complexity of selection sort algorithm is

- Worst case: O(N^2) comparisons but O(N) swaps
- Average Case: Ɵ(N^2) comparisons but O(N) swaps
- Best case: Ω(N^2) comparisons but no swaps
- Space Complexity: Ɵ(1) constant

The best thing about this algorithm is that it always makes at most N swaps and hence, can be used when memory write is a costly operation.

**Optimized Selection Sort Implementation:**

#include <stdio.h> void swap(int* x, int* y) { int temp = *x; *x = *y; *y = temp; } void selection_sort(int arr[], int n) { int i, j, smallest; for (i = 0; i < n - 1; i++) { smallest = i; for (j = i + 1; j < n; j++) { if (arr[j] < arr[smallest]) smallest = j; } swap(&arr[smallest], &arr[i]); } } int main() { int arr[] = { 12, 8, 5, 10, 13, 9 }; int n = sizeof(arr) / sizeof(arr[0]); printf("\nInput Array:\n"); for (int i = 0; i < n; i++) printf("%d ", arr[i]); selection_sort(arr, n); printf("\nSorted Array:\n"); for (int i = 0; i < n; i++) printf("%d ", arr[i]); return 0; }

**Output:**

Input Array: 12 8 5 10 13 9 Sorted Array: 5 8 9 10 12 13

**Applications:**

- Better than Insertion sort in performance as the number of swaps is at most
*N*in selection as compared to*N^2*in insertion sort. - It can be used where writes are more expensive than reads, such as in EEPROM and Flash memory where the write operation lessens the lifespan of memory.
- It is not preferred over bubble sort and gnome sort due to higher time complexity.

TOP Interview Coding Problems/Challenges

- Run-length encoding (find/print frequency of letters in a string)
- Sort an array of 0's, 1's and 2's in linear time complexity
- Checking Anagrams (check whether two string is anagrams or not)
- Relative sorting algorithm
- Finding subarray with given sum
- Find the level in a binary tree with given sum K
- Check whether a Binary Tree is BST (Binary Search Tree) or not
- 1[0]1 Pattern Count
- Capitalize first and last letter of each word in a line
- Print vertical sum of a binary tree
- Print Boundary Sum of a Binary Tree
- Reverse a single linked list
- Greedy Strategy to solve major algorithm problems
- Job sequencing problem
- Root to leaf Path Sum
- Exit Point in a Matrix
- Find length of loop in a linked list
- Toppers of Class
- Print All Nodes that don't have Sibling
- Transform to Sum Tree
- Shortest Source to Destination Path

Comments and Discussions

**Ad:**
Are you a blogger? Join our Blogging forum.