The algorithm:

This is a basic sorting algorithm which repeatedly finds the smallest number and replaces it with the number on the first index, then the second index and so on.

In this algorithm we first find the smallest number and replace it with the number at the first index.

Next, we find the smallest number in the part of the array after the first index. We replace this number with the number at the second of the array.

We repeat this process until we have a sorted array left.

Example:

Consider the following array:

[7 , 8 , 4 , 5]

We start by searching for the smallest number. We find that it is 4. Hence, we switch it with the number at index 0, i.e., 7. The modified array becomes:

[4 , 8 , 7 , 5]

Next, we look for the smallest number in the array after index 0, i.e., [8 , 7 , 5]. We find that it is 5. Thus, we replace 5 with the number at index 1, i.e., 8. The modified array becomes:

[4 , 5 , 7 , 8]

This is a completely sorted array and hence the program is stopped.

The program:

 #include <iostream>
#include <vector>
using namespace std;
 
int main()
{
    cout << "Enter the 10 elements in the array:" << endl;
    vector<int> a(10);
    for (int i = 0; i<10 ; i++){
        int x;
        cin >> x;
        a[i] = x;
    }
    for (int i = 0 ; i < 10 ; i++){
        int m = a[i];
        int ch = i;
        for (int j = i+1 ; j < 10 ; j++){
            if (a[j]<m){
                m = a[j];
                ch = j;
            }
        }
        int t = a[i];
        a[i] = m;
        a[ch] = t;
 
    }
    for (int i = 0; i<10 ; i++){
        cout << a[i] << " ";
    }
}

The output of the above program is:

Time Complexity: O(n2)

The github link for the above program is:

https://github.com/HSNA243/C-Programs/blob/master/SelectionSort.cpp

Visits: 64

Leave a Reply

Your email address will not be published. Required fields are marked *