Selection sort in C++, What is selection sort?

Selection sort performs sorting by repeatedly putting the largest element in the unprocessed portion of the array to the end of the this unprocessed portion until the whole array is sorted.

In a loop, the highest element from the unsorted zone is selected (hence the name Selection Sort) and placed at the end of the unsorted zone. We begin by selecting the largest element and moving it to the highest index position. We can do this by swapping the element at the highest index and the largest element.

The run time is Θ(n²), where n is the number of elements. The number of swaps is O(n).

C++ CodeC Code

#include <iostream>
using namespace std;

int main()
{
int array[9]={4,3,5,1,2,0,7,9,4};
for(int i=0; i<9; i++)
{
int min = i;
for(int j=i; j<9; j++)
if(array[min]<array[j])
min = j;

swap(array[min],array[i]);
}

for(int i=0; i<9;i++)
cout << array[i] << endl;
}


4 Responses to “What is Selection sort and how does it work? Selection sort algorithm”  

  1. 1 aditya

    well done…its nice…my all doubts are cleared

  2. 2 Asfandiar Ali

    I checked your script but it isnt giving any output on the screen when its run.
    So can u tell y.

  3. 3 Daniele Simonin

    Recursive version (that we can resolve with telescoping) has:

    T(n)=T(n-1) O(n)

    the run time is Θ(n²).

    It’s a bad algorithm because it has quadratic complexity in worst-case and best-case.

  4. 4 programmer

    i wanna know more about linear selection sort,heap sort,bubble sort and quick sort

Leave a Reply


*
To prove you're a person (not a spam script), type the security word shown in the picture.
Anti-Spam Image