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 using Selection Sort.

Algorithm / Approach

  1. Initialize an unsorted array.
  2. Run an outer loop i from 0 up to size - 1.
  3. Run an inner loop j starting immediately after i (j = i + 1) to the end.
  4. Compare the element at i against every element at j.
  5. If ar[i] > ar[j], swap them immediately.
  6. Print the fully sorted array.
main.cpp
#include<iostream>
 using namespace std;
int main(){
 int i,j,temp;
 int ar[5] = {25,17,31,13,2};
 cout<<"BEFORE SORTING :\n";
 for(i=0; i < 5; i++) {
   cout<< 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;
	}
   }
 }

 cout<<"\n\nAFTER SORTING :\n";
 for(i=0; i < 5; i++) {
  cout<< 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 divides the array into a sorted portion and an unsorted portion. It continuously scans the unsorted portion, selects the smallest element it can find, and swaps it into the sorted portion.
  • Note on the provided code: This implementation eagerly swaps the elements the moment it finds a smaller one. A more optimized standard Selection Sort will just record the *index* of the minimum value during the inner loop, and then perform exactly ONE single swap at the end of the outer loop.

Complexity

Time Complexity O(n^2)
Space Complexity O(1)
ADVERTISEMENT