ankittmeena

Ankit Kumar Meena

Posted on June 29, 2023

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
💖 💪 🙅 🚩
ankittmeena
Ankit Kumar Meena

Posted on June 29, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Selection Sort
beginners Selection Sort

June 29, 2023