C++ Program For Selection Sort

Selection sort is conceptually the most simplest sorting algorithm. This algorithm will first find the smallest element in the array and swap it with the element in the first position, then it will find the second smallest element and swap it with the element in the second position, and it will keep on doing this until the entire array is sorted.

It is called selection sort because it repeatedly selects the next-smallest element and swaps it into the right place. 

C++ Program For Selection Sort, selection sort, sorting, sorting in c++

Program:

#include <iostream>
using namespace std;

 
void swap (int arr[], int i, int j, int n)	//function to swap
{
  
    int temp = arr[i];
  
    arr[i] = arr[j];
  
    arr[j] = temp;

} 

void selection (int arr[], int n)	//function to sort the array
{
  
    for (int i = 0; i < n; i++)
    {
        for (int j = i + 1; j < n; j++)
	    {
              if (arr[i] > arr[j])
                swap (arr, i, j, n);
        }
    
    }

}

int main () 
{
  
    int n;
  
    cout << "Enter size of array: ";
  
    cin >> n;
  
    int arr[n];
    
    cout << "Enter array elements:" << endl;
    
    for (int i = 0; i < n; i++)
       cin >> arr[i];
  
 
    selection (arr, n);	//fuction call
  
    cout << "Sorted array:" << endl;
  
 
    for (int i = 0; i < n; i++)	//printing sorted array
       cout << arr[i] << " ";

    return 0;
}

Output:

Enter size of array: 5

Enter array elements:
5 4 3 2 1

Sorted array:
1 2 3 4 5

C++ Program For Selection Sort C++ Program For Selection Sort Reviewed by Beast Coder on February 19, 2021 Rating: 5

No comments:

Powered by Blogger.