dev-resources.site
for different kinds of informations.
Selection Sort
Published at
6/29/2023
Categories
beginners
cpp
algorithms
selectionsort
Author
Ankit Kumar Meena
Main Article
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:
- Start with the unsorted portion consisting of the entire array.
- Find the smallest element in the unsorted portion.
- Swap the smallest element with the first element of the unsorted portion.
- Expand the sorted portion by one element and reduce the unsorted portion by one element.
- 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;
}
Articles
12 articles in total
Getting Started with Docker: A Guide for Developers
read article
Mastering Fragments in Java for Android Development
read article
Mastering RecyclerView in Java for Android Development
read article
Understanding Adapters in Java for Android Development
read article
My Journey in Android Development: Learning Java and Building Apps
read article
Merge Sort
read article
Selection Sort
currently reading
Bubble Sort
read article
Insertion Sort
read article
The Artistry of Front-End Development: Building Captivating User Experiences
read article
Demystifying Cloud Computing: A Comprehensive Guide
read article
Hi!
read article
Featured ones: