Published: 19 Feb 2025 | Reading Time: 7 min read
The C Program for Selection Sort is a widely used approach in computer science for arranging elements in ascending order. This algorithm works by repeatedly finding the smallest element from an unsorted section and swapping it with the first unsorted element.
This comprehensive guide covers everything you need to know about Selection Sort, from understanding what Selection Sort is to exploring its implementation in C program.
Selection Sort is one of the simplest sorting algorithms used to arrange elements in ascending or descending order. It is a comparison-based algorithm that repeatedly selects the smallest (or largest) element from the unsorted portion of the list and moves it to the sorted portion. While it is not the most efficient for large datasets, its simplicity makes it a popular choice for learning the basics of sorting algorithms.
Selection Sort operates by systematically dividing the array into two sections: a sorted part and an unsorted part. At the start, the sorted part is empty, and the unsorted part contains all the elements of the array. With each iteration, one element is selected from the unsorted part, identified as the smallest (or largest, depending on sorting order), and moved to the sorted part.
Here is a step-by-step explanation of sorting the array [29, 10, 14, 37, 13] in ascending order using Selection Sort in C:
Initial Array:
[29, 10, 14, 37, 13]
We will sort the array by finding the smallest element in the unsorted part and swapping it with the first unsorted element.
Unsorted portion: [29, 10, 14, 37, 13]
Compare each element:
Swap 10 with the first element (29):
Array after Step 1: [10, 29, 14, 37, 13]
Unsorted portion: [29, 14, 37, 13]
Compare each element:
Swap 13 with the first unsorted element (29):
Array after Step 2: [10, 13, 14, 37, 29]
Unsorted portion: [14, 37, 29]
Compare each element:
No swap is needed.
Array after Step 3: [10, 13, 14, 37, 29]
Unsorted portion: [37, 29]
Compare:
Swap 29 with 37:
Array after Step 4: [10, 13, 14, 29, 37]
Final Sorted Array: [10, 13, 14, 29, 37]
Each step confirms the smallest element is placed in its correct position, and the process continues until the array is sorted.
Here is a complete implementation of the Selection Sort C code. This code sorts an array of integers in ascending order by repeatedly finding the smallest element in the unsorted portion and swapping it with the first unsorted element.
#include <stdio.h>
// Function to perform selection sort
void selectionSort(int arr[], int n) {
int i, j, min_idx;
// Traverse through all array elements
for (i = 0; i < n - 1; i++) {
// Find the minimum element in the unsorted portion
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
int temp = arr[min_idx];
arr[min_idx] = arr[i];
arr[i] = temp;
}
}
// Function to print an array
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
// Main function
int main() {
int arr[] = {64, 25, 12, 22, 11};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Original array: \n");
printArray(arr, n);
selectionSort(arr, n);
printf("Sorted array: \n");
printArray(arr, n);
return 0;
}
int arr[] = {64, 25, 12, 22, 11};
The program shows the implementation of the Selection Sort algorithm in C. Selection Sort is a simple sorting technique that iterates through the array and divides it into two parts: the sorted part and the unsorted part. With each pass, the smallest element from the unsorted portion is identified and moved to its correct position in the sorted part by swapping it with the first unsorted element.
The selectionSort function is the core of the program. It takes two arguments: the array arr[] to be sorted and its size n. The outer loop iterates through the array from the first to the second-to-last element. For each iteration, the function assumes the current element (indexed by i) is the smallest in the unsorted portion.
The printArray function is a utility function used to display the contents of an array. It accepts the array and its size as arguments. Using a for loop, it iterates through each element in the array, printing them one by one, separated by spaces.
The main function initializes an integer array, arr, with a set of predefined values: {64, 25, 12, 22, 11}. It calculates the size of the array using the formula sizeof(arr) / sizeof(arr[0]), which divides the total memory size of the array by the size of a single element.
Original array:
64 25 12 22 11
Sorted array:
11 12 22 25 64
A recursive implementation of Selection Sort is a version of the algorithm that sorts an array by repeatedly calling itself on smaller portions of the array. Instead of using loops to iterate through the array, the function breaks the problem into smaller subproblems and solves them recursively.
#include <stdio.h>
// Recursive function to perform selection sort
void recursiveSelectionSort(int arr[], int n, int index) {
// Base case: If the entire array is sorted
if (index == n - 1) {
return;
}
// Find the minimum element in the unsorted portion
int min_idx = index;
for (int j = index + 1; j < n; j++) {
if (arr[j] < arr[min_idx]) {
min_idx = j;
}
}
// Swap the smallest element with the current index
int temp = arr[min_idx];
arr[min_idx] = arr[index];
arr[index] = temp;
// Recursive call for the remaining unsorted portion
recursiveSelectionSort(arr, n, index + 1);
}
// Main function
int main() {
int arr[] = {64, 25, 12, 22, 11};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Original array: \n");
printArray(arr, n);
recursiveSelectionSort(arr, n, 0);
printf("Sorted array: \n");
printArray(arr, n);
return 0;
}
int arr[] = {64, 25, 12, 22, 11};
This program implements the Selection Sort algorithm recursively. Instead of using iterative loops for sorting, the program employs a recursive function, recursiveSelectionSort, to sort the array.
The function recursiveSelectionSort sorts an array arr[] by processing one element at a time, starting from the current index and moving towards the end of the array.
The printArray function is important for displaying the array contents before and after sorting. It iterates through the array and prints each element separated by spaces. This function is reused from the previous iterative version to maintain consistency.
The main function initializes an unsorted array arr[] with predefined values: {64, 25, 12, 22, 11}. It calculates the size of the array and prints the original array using printArray.
Original array:
64 25 12 22 11
Sorted array:
11 12 22 25 64
Selection Sort can be implemented using functions to improve code modularity and readability. By defining a separate function for selection sort, we can call it multiple times as needed. This approach helps in keeping the main() function clean and easy to understand.
#include <stdio.h>
void selectionSort(int arr[], int n) {
int i, j, minIdx, temp;
for (i = 0; i < n - 1; i++) {
minIdx = i;
for (j = i + 1; j < n; j++) {
if (arr[j] < arr[minIdx]) {
minIdx = j;
}
}
temp = arr[minIdx];
arr[minIdx] = arr[i];
arr[i] = temp;
}
}
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: ");
printArray(arr, n);
return 0;
}
Input Array: {64, 25, 12, 22, 11}
Sorted array: 11 12 22 25 64
In Selection Sort, the findmax function can be used to find the maximum element in a given range of an array. Instead of searching for the minimum element (as in traditional Selection Sort), we can modify the function to locate the maximum element and place it at the correct position.
#include <stdio.h>
int findMax(int arr[], int n) {
int maxIdx = 0;
for (int i = 1; i < n; i++) {
if (arr[i] > arr[maxIdx]) {
maxIdx = i;
}
}
return maxIdx;
}
int main() {
int arr[] = {10, 3, 5, 7, 2};
int n = sizeof(arr) / sizeof(arr[0]);
int maxIndex = findMax(arr, n);
printf("Maximum element is at index: %d, Value: %d\n", maxIndex, arr[maxIndex]);
return 0;
}
Input Array: {10, 3, 5, 7, 2}
Maximum element is at index: 0, Value: 10
This implementation moves the selection sort logic outside the main() function, making the program more structured.
#include <stdio.h>
void selectionSort(int arr[], int n);
void swap(int *a, int *b);
int main() {
int arr[] = {29, 10, 14, 37, 13};
int n = sizeof(arr) / sizeof(arr[0]);
selectionSort(arr, n);
printf("Sorted array: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
void selectionSort(int arr[], int n) {
int i, j, minIdx;
for (i = 0; i < n - 1; i++) {
minIdx = i;
for (j = i + 1; j < n; j++) {
if (arr[j] < arr[minIdx]) {
minIdx = j;
}
}
swap(&arr[minIdx], &arr[i]);
}
}
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
Input Array: {29, 10, 14, 37, 13}
Sorted array: 10 13 14 29 37
A for loop is commonly used in Selection Sort to iterate through the array and find the minimum element in each pass.
#include <stdio.h>
void selectionSort(int arr[], int n) {
for (int i = 0; i < n - 1; i++) {
int minIdx = i;
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[minIdx]) {
minIdx = j;
}
}
int temp = arr[minIdx];
arr[minIdx] = arr[i];
arr[i] = temp;
}
}
int main() {
int arr[] = {8, 4, 6, 2, 9};
int n = sizeof(arr) / sizeof(arr[0]);
selectionSort(arr, n);
printf("Sorted array: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
Input Array: {8, 4, 6, 2, 9}
Sorted array: 2 4 6 8 9
A while loop can also be used to implement Selection Sort instead of a for loop.
#include <stdio.h>
void selectionSort(int arr[], int n) {
int i = 0;
while (i < n - 1) {
int minIdx = i;
int j = i + 1;
while (j < n) {
if (arr[j] < arr[minIdx]) {
minIdx = j;
}
j++;
}
int temp = arr[minIdx];
arr[minIdx] = arr[i];
arr[i] = temp;
i++;
}
}
int main() {
int arr[] = {50, 20, 40, 10, 30};
int n = sizeof(arr) / sizeof(arr[0]);
selectionSort(arr, n);
printf("Sorted array: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
Input Array: {50, 20, 40, 10, 30}
Sorted array: 10 20 30 40 50
Selection Sort offers several benefits that make it a very good option in certain situations. Here are some of the key advantages of using this sorting algorithm:
Selection Sort is one of the simplest sorting algorithms, making it easy to understand and implement. Its direct approach of repeatedly finding the minimum element and swapping it with the current position confirms clarity in both logic and coding. This simplicity also makes it an excellent choice for beginners learning sorting algorithms.
The algorithm does not require any additional memory or auxiliary data structures for sorting. Since it sorts the array in place by swapping elements, it has a space complexity of O(1), which is beneficial in memory-constrained systems.
Selection Sort performs well on small datasets where its inefficiencies in terms of comparisons and swaps do not significantly impact performance. For cases where simplicity and low memory usage are prioritized over speed, this algorithm is suitable.
While Selection Sort has its advantages, it also comes with certain drawbacks that make it less suitable for other situations. Here are some of the key disadvantages of using this sorting algorithm:
Selection Sort has a time complexity of O(n²) in all cases—best, average, and worst. This quadratic time complexity means that its performance reduces rapidly as the size of the dataset increases which makes it unsuitable for sorting large datasets.
Selection Sort is not a stable sorting algorithm. Stability refers to maintaining the close order of elements with equal keys. Since the algorithm swaps elements, it can disturb the original order of identical elements, which can be undesirable in certain applications.
The algorithm performs the same number of comparisons and swaps still of the initial arrangement of elements. This non-adaptive behavior makes it inefficient for datasets that are already sorted or entirely sorted.
Selection Sort is useful in specific contexts where its simplicity and characteristics are beneficial. Here are some common applications where this algorithm can be effectively used:
Selection Sort is taught in computer science courses to introduce sorting algorithms. Its simplicity helps students hold fundamental concepts like comparison, swapping, and algorithmic analysis.
In scenarios where datasets are small, the overhead of more complex algorithms does not justify their use. Selection Sort's simplicity and ease of implementation make it ideal for sorting small collections where performance is not a critical factor.
Since Selection Sort has a space complexity of O(1), it is particularly useful in environments where memory resources are limited. For embedded systems or low-memory devices, its low-memory requirements outweigh its inefficiency for larger datasets.
Selection Sort is an excellent starting point for understanding sorting algorithms. It acts as a foundation for more advanced techniques. By implementing Selection sorting in various ways, such as iterative and recursive methods, programmers can learn about algorithm design and optimization.
Selection Sort is a simple sorting algorithm that repeatedly finds the smallest (or largest) element in the unsorted portion of the list and swaps it with the first unsorted element. This process continues until the entire list is sorted.
Sorting in C refers to arranging elements of an array or list in a specific order (ascending or descending). It can be implemented using algorithms like Bubble Sort, Selection Sort, Merge Sort, and QuickSort, either manually or using built-in libraries.
Selection Sort is simple to implement, works well on small datasets, and doesn't require extra memory for sorting. It is also useful when memory writes are costly, as it minimizes the number of swaps.
The time complexity of Selection Sort is O(n²) for both best and worst cases, as it involves nested loops to find the minimum element and perform swaps.
Selection Sort is best used for small datasets or when minimizing memory writes is required, such as in systems with limited resources or flash memory devices.
Selection Sort is an in-place, comparison-based algorithm that is not adaptive or stable by default. It performs well on small datasets but is inefficient for large ones.
Selection Sort works by dividing the array into two parts: sorted and unsorted. It repeatedly finds the smallest element in the unsorted part and swaps it with the first unsorted element in the sorted portion.
Complete Guide on String Functions in C - Learn essential string functions in C with syntax, examples, memory rules, and safe practices. (29 Dec 2025, 5 min read)
Mastering Insertion Sort in C: Code, Logic, and Applications - Understand insertion sort in C with easy-to-follow logic, code examples, and practical tips. (29 Dec 2025, 6 min read)
Quick Sort Algorithm Explained: Steps, Code Examples and Use Cases - Learn the Quick Sort Algorithm with clear steps, partition logic, Python & C++ code examples. (28 Dec 2025, 6 min read)
Switch Statement in C: Syntax, Flowchart & Sample Programs - Learn how to use the switch statement in C programming with simple syntax and real-life examples. (27 Dec 2025, 6 min read)
The Ultimate Guide to Binary Search Algorithm in C - Learn the Binary Search Algorithm with steps, examples, and efficiency insights. (27 Dec 2025, 8 min read)
Merge Sort in C: A Step-by-Step Guide with Code Examples - Learn how Merge Sort works in C with easy-to-follow examples and step-by-step logic. (26 Dec 2025, 8 min read)
NxtWave is a technology education platform offering comprehensive courses in software development, data structures, algorithms, and modern programming practices. The platform provides industry-recognized certifications and practical learning experiences for students and professionals.
Contact Information:
Course Offerings: