• Selection Sorting work as arranging array data selecting one by one.
  • In an unsorted array, search for the minimum value of the element and put it in the beginning and swap with the first element.
  • Again from the remaining unsorted array element, we search for the minimum value of the element and put it before the unsorted subarray and swaping will be doing.

 

 

selectionsort

  • From the above image, we take an example.
  • Here we sort the array in increasing order so we take an unsorted array.
  • Then select the minimum value element and put at the beginning so we select 10 that is smaller in an unsorted array and put at the beginning and 25 swap with 10 element.
  • Same we do for rest of the unsorted arrays so we get a select minimum value element of an unsorted array that is 15 and we put after 10 and swaping between  15 and  21.
  • The same way we do for the rest of the unsorted array and get sorted array in increasing order.
  • If you want to arrange an array in descending order so you select the maximum value element instead of minimum value element.

SOME IMPORTANT KEY POINT ABOUT SELECTION SORTING

  1. Time Complexity: O(n^2) because of two-loop used in below program.
  2. Auxiliary Space: O(n)
  3. In Place: For Sorting does not any extra space for that.

 

#include <iostream>

using namespace std;

int main()
{
    
    int n,i,j;
    int arr[n];
    
    cout<<"Enter the Number of element";
    cin>>n;
    //Enter element in the array
    for(i=0;i<n;i++)
    {
        cin>>arr[i];
    }
    
    // Here we take one by one value of unsorted array 
    //Here we take n-1 value because we take j = i+1 when i = n-1 then j = n 
    for(i=0;i<n-1;i++)
    {
        int min = i;
        
        for(j=i+1;j<n;j++)
        {
            //find minimum element from unsorted array
           if(arr[j]<arr[min])
            {
                min = j;
            }
        }
        
        // swap minimum element with first element
        int temp = arr[i];
          arr[i] = arr[min];
        arr[min] = temp;
    }
    // print sorted array
    for(i=0;i<n;i++)
    {
        cout<<arr[i]<<" ";
    }
    

    return 0;
}
 

Output :
Enter the Number of element 5                                                                                                 
25 21 26 10 15                                                                                                                
10 15 21 25 26

Leave a Reply

%d bloggers like this: