Selection Sort C++

 Selection Sort Code In C++

The main idea of ​​the selection sort is to select the number of the first position at the beginning. Then you have to look at the numbers after this one by one. If it is found that the next number is smaller than the number in the selected position, then the two numbers need to be swapped.

When all the numbers are viewed in this way, the selected position must have the smallest number.

This time by selecting the number of the second position, you have to check with all the other numbers. Later the number will have to be changed as before. Thus each number becomes sorted.

The implementation of selection sort will be discussed below in c++ language.

1. First of all, we have to take the input array of the n-length.

    cin>>n;
    for(i=0;i<n;i++)
    {
        cin>>numbers[i];
    }

2. Now the main idea described, in the beginning, will be implemented. Please, read carefully the beginning section to understand the below code,

    for (i=0; i<n; i++)
    {
        for (j=i+1; j<=n; j++)
        {
            if (numbers[i]>numbers[j])
            {
                swap(numbers[i], numbers[j]);
            }
        }
    }

3. After the sorting process, we will be printed the sorted array below.

    for(i=0;i<n;i++)
    {
        cout<<numbers[i]<<" ";
    }


Now, the full code of the selection sort in c++ language give below.

#include <bits/stdc++.h>
using namespace std;
int main()
{
    int i, j, n, numbers[500];
    cin>>n;
    for(i=0;i<n;i++)
    {
        cin>>numbers[i];
    }
    for (i=0; i<n; i++)
    {
        for (j=i+1; j<=n; j++)
        {
            if (numbers[i]>numbers[j])
            {
                swap(numbers[i], numbers[j]);
            }
        }
    }

    for(i=0;i<n;i++)
    {
        cout<<numbers[i]<<" ";
    }
    cout<<endl;
    return 0;
}

Read Similar Post:
1. The Beginning of C++
2. 15 puzzles in C++
3. N Queen in C++
4. Minimum Edit Distance in C++
5. Longest Common Subsequence in C++
6. Quick Sort in C++
7. Merge Sort in C++
8. Bubble Sort in C++

Post a Comment

Previous Post Next Post