C++ Programming Code Examples C++ > Sorting Searching Code Examples C++ Program to Implement Selection Sort C++ Program to Implement Selection Sort This is a C++ program to sort the given data using Selection Sort. - Selection sort algorithm sort data by comparing one element to every other element and decide its position. - The time complexity of this algorithm is O(n^2). - Starting from the beginning pick one number. - Compare it with others one by one. - replace if the other number is lesser than this one. - Display the result. - Exit. #include <iostream> using namespace std; // Sort arr[] of size n using Selection Sort. void SelectionSort (int arr[], int n) { int i, j; for (i = 0; i < n; ++i) { for (j = i+1; j < n; ++j) { // Comparing consecutive data and switching values if value at i > j. if (arr[i] > arr[j]) { arr[i] = arr[i]+arr[j]; arr[j] = arr[i]-arr[j]; arr[i] = arr[i]-arr[j]; } } // Value at i will be minimum of all the values above this index. } } int main() { int n, i; cout<<"\nEnter the number of data element to be sorted: "; cin>>n; int arr[n]; for(i = 0; i < n; i++) { cout<<"Enter element "<<i+1<<": "; cin>>arr[i]; } SelectionSort(arr, n); // Display the sorted data. cout<<"\nSorted Data "; for (i = 0; i < n; i++) cout<<"->"<<arr[i]; return 0; }