# Selection Sort in C++

Selection sort is a technique which is used to sort the array in ascending order. The whole array is divided into two parts in the selection sort algorithm. One part is sorted in ascending order. The other part is unsorted array.

The algorithm searches the minimum element in the unsorted array and swaps the element to the sorted array. The disadvantage of this method is time complexity and space complexity.

Swapping of elements is nothing but exchange two elements in an array. Swapping is used for sorting an array, reverse the string or numbers.

## Selection Sort in C++

``````#include<iostream>
using namespace std;
void swapping(int &a, int &b) {         //swap the content of a and b
int temp;
temp = a;
a = b;
b = temp;
}
void display(int *array, int size) {
for(int i = 0; i<size; i++)
cout << array[i] << " ";
cout << endl;
}
void selectionSort(int *array, int size) {
int i, j, imin;
for(i = 0; i<size-1; i++) {
imin = i;   //get index of minimum data
for(j = i+1; j<size; j++)
if(array[j] < array[imin])
imin = j;
//placing in correct position
swap(array[i], array[imin]);
}
}
int main() {
int n;
cout << "Enter the number of elements: ";
cin >> n;
int arr[n];           //create an array with given number of elements
cout << "Enter elements:" << endl;
for(int i = 0; i<n; i++) {
cin >> arr[i];
}
cout << "Array before Sorting: ";
display(arr, n);
selectionSort(arr, n);
cout << "Array after Sorting: ";
display(arr, n);
}``````
`Read Also : C++ Program to Display Fibonacci Sequence`

## Output

The screen asks you to enter the number of elements. If you enter number of elements then it asks you to enter the elements. After sorting the array it displays the unsorted array and sorted array.

``````Enter the number of elements: 6
Enter elements:
5 9 7 23 78 20
Array before Sorting: 5 9 7 23 78 20
Array after Sorting: 5 7 9 20 23 78``````