selection sort

PHOTO EMBED

Thu May 22 2025 03:35:24 GMT+0000 (Coordinated Universal Time)

Saved by @RohitChanchar #c++

// You are using GCC
#include<bits/stdc++.h>
using namespace std;
int main(){
    int n;
    cin>>n;
    int arr[n];
    for(int i=0;i<n;i++){
        cin>>arr[i];
    }
    cout<<"sorted array after selection sort:";
    for(int i=0;i<n;i++){
        int index=i;
        for(int j=i+1;j<n;j++){
            if(arr[j]<arr[index] || arr[j]==arr[index]){
                index=j;
            }
        }
        swap(arr[i],arr[index]);
        cout<<arr[i]<<" ";
    }
    return 0;
}
content_copyCOPY

This is a C++ implementation of selection sort. In each iteration, the smallest (or equal smallest) element from the unsorted portion of the array is found and swapped with the current position. This process is repeated until the array is completely sorted. The code reads an array of size n, sorts it using selection sort without built-in sorting functions, and prints the sorted array as elements are placed in their correct positions.