DEV Community

Cover image for Selection Sort
Ankit Kumar Meena
Ankit Kumar Meena

Posted on

1

Selection Sort

Selection Sort:

Selection sort is a simple comparison-based sorting algorithm. It works by dividing the input array into two parts: the sorted portion at the beginning and the unsorted portion at the end. The algorithm repeatedly selects the smallest element from the unsorted portion and swaps it with the element at the beginning of the unsorted portion, expanding the sorted portion by one element. This process is repeated until the entire array is sorted.

Here's the step-by-step procedure for selection sort:

  1. Start with the unsorted portion consisting of the entire array.
  2. Find the smallest element in the unsorted portion.
  3. Swap the smallest element with the first element of the unsorted portion.
  4. Expand the sorted portion by one element and reduce the unsorted portion by one element.
  5. Repeat steps 2-4 until the unsorted portion becomes empty.

C++ Code(Iterative):

#include<iostream>
using namespace std;
void selection_sort(int arr[],int n){
    for (int i = 0; i < n-1; i++)
    {
        int min_index=i;
        for (int j = i; j <= n-1; j++)
        {
            if (arr[j]<arr[min_index])
            {
                min_index=j;
            }            
        }  
        swap(arr[i],arr[min_index]);      
    }   
}
int main()
{
    int n;
    cin>>n;
    int arr[1000];
    for (int i = 0; i < n; i++)
    {
        cin>>arr[i];
    }

    selection_sort(arr,n);
    for (int i = 0; i < n; i++)
    {
        cout<<arr[i]<<" ,";
    }
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs