C++ selection sorting algorithm example

  • 2020-04-02 02:49:00
  • OfStack

Selection sort

Selection sort is a simple and intuitive sorting algorithm, which works as follows. Find the smallest (large) element in the unsorted sequence, store it at the beginning of the sorted sequence, then continue to look for the smallest (large) element from the remaining unsorted elements, and place it at the end of the sorted sequence. And so on, until all the elements are sorted.

The main advantages of selection sort relate to data movement. If an element is in the correct final position, it will not be moved. Select sort each time a pair of elements are exchanged, at least one of them will be moved to its final position, so sorting a table of n elements is exchanged at most n-1 times in total. Of all the sorting methods that rely entirely on swapping to move elements, selection sort is a good one. The time complexity of the selection sort is also order n^2.

Code implementation


#include <iostream>
using namespace std;
 
void SelectSort(int arr[], int length)
{
     int temp, min;
     for (int i = 0; i < length - 1; ++i)
     {
          min = i;
 
          //Find the minimum
          for (int j = i + 1; j < length; ++j)
          {
               if (arr[j] < arr[min])
                    min = j;
          }
 
          //Exchange < br / >           if (min != i)
          {
               temp = arr[i];
               arr[i] = arr[min];
               arr[min] =temp;
          }
     }
}
 
int main()
{
     int arr[10] = {2, 4, 1, 0, 8, 4, 8, 9, 20, 7};
 
     SelectSort(arr, sizeof(arr) / sizeof(arr[0]));
 
     for (int i = 0; i < sizeof(arr) / sizeof(arr[0]); ++i)
     {
          cout<<arr[i]<<" ";
     }
     cout<<endl;
 
     return 0;
}


Related articles: