Skip to main content

ProwessApps

Learn · Practice · Excel

Arrange the array elements in ACS order using "Selection Sort".

C Code Example — Data Structure Programs

ADVERTISEMENT

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

  1. Initialize an unsorted array.
  2. Start an outer loop i from 0 to length - 1.
  3. Start an inner loop j from i + 1 to the end of the array.
  4. Compare the element at the current i position with every element in j: if(ar[i] > ar[j]).
  5. If a smaller element is found, immediately swap them.
  6. 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.
ADVERTISEMENT