Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
C Program for Selection Sort?
The selection sort is a simple sorting algorithm that works by finding the smallest element from the unsorted portion of the array and placing it at the beginning. This process is repeated until the entire array is sorted.
Syntax
void selectionSort(int arr[], int n) {
for (int i = 0; i < n-1; i++) {
int minIndex = i;
for (int j = i+1; j < n; j++) {
if (arr[j] < arr[minIndex])
minIndex = j;
}
// Swap elements
int temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
}
How Selection Sort Works
Let's understand the algorithm with an array {20, 12, 23, 55, 21} −
- Find minimum: Compare all elements and find the smallest (12)
- Swap: Place the minimum at the first position
- Repeat: Continue with the remaining unsorted portion
Example
Here's a complete C program implementing selection sort −
#include <stdio.h>
void selectionSort(int arr[], int n) {
int i, j, minIndex, temp;
for (i = 0; i < n-1; i++) {
minIndex = i;
// Find minimum element in remaining array
for (j = i+1; j < n; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
// Swap minimum element with first element
if (minIndex != i) {
temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
}
}
void printArray(int arr[], int n) {
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("<br>");
}
int main() {
int arr[] = {6, 12, 0, 18, 11, 99, 55, 45, 34, 2};
int n = 10;
printf("Original array: ");
printArray(arr, n);
selectionSort(arr, n);
printf("Sorted array: ");
printArray(arr, n);
return 0;
}
Original array: 6 12 0 18 11 99 55 45 34 2 Sorted array: 0 2 6 11 12 18 34 45 55 99
Time Complexity
| Case | Time Complexity | Space Complexity |
|---|---|---|
| Best Case | O(n²) | O(1) |
| Average Case | O(n²) | O(1) |
| Worst Case | O(n²) | O(1) |
Conclusion
Selection sort is simple to understand but inefficient for large datasets with O(n²) time complexity. It performs well on small arrays and requires only O(1) extra memory space.
Advertisements
