Arrange the array elements in ACS order using "Selection Sort".
Objective
Write a C program to sort an array in ascending order using Selection Sort.
Algorithm / Approach
- Initialize an unsorted array.
- Start an outer loop
ifrom 0 tolength - 1. - Start an inner loop
jfromi + 1to the end of the array. - Compare the element at the current
iposition with every element inj:if(ar[i] > ar[j]). - If a smaller element is found, immediately swap them.
- Repeat until the entire array is sorted.
main.c
#include<stdio.h>
int main(){
int i,j,temp;
int ar[5] = {25,17,31,13,2};
printf("BEFORE SORTING :\n");
for(i=0; i < 5; i++) {
printf("%d ",ar[i]);
}
for(i=0; i < 5-1;i++){
for(j=i+1; j < 5; j++){
if(ar[i]>ar[j]){
temp=ar[i];
ar[i]=ar[j];
ar[j]=temp;
}
}
}
printf("\n\nAFTER SORTING :\n");
for(i=0; i < 5; i++) {
printf("%d ",ar[i]);
}
return 0;
}
Expected Output
BEFORE SORT : 25 17 31 13 2 AFTER SORT : 2 13 17 25 31
Explanation of the Program
- Selection Sort works by scanning the unsorted portion of the list, finding the absolute smallest element, and placing it at the very front.
- Notice the difference from Bubble sort: instead of swapping adjacent elements, the outer loop locks onto a single position (
i), and the inner loop checks all remaining elements to see if any of them should be moved into that locked position.
Complexity
Time Complexity
O(n^2) - It always scans the entire remaining array to find the minimum.
Space Complexity
O(1) - In-place sorting.