Computer Scientists are Pretty Pessimistic

Friday 17 June 2016

Selection Sort (Knock Out Algorithm)

Algorithm ::


l ← n       ( here n is number of elements )
newindex ← n
while l ≠ 0 do
       index ← 1
       for i=2 to n do
             if aindex ≤ ai
                        index ← i
        xnewindex ← aindex      ( here x is the new array )
        newindex ← newindex – 1
        aindex ← -∞
        l ← l -1



CODE :: 

#include <iostream>
#include <climits>
using namespace std;
int main()
{
    int arr[100],newarr[100],n;
    cout<<"Enter number of elements: "<<endl;
    cin>>n;
    cout<<"Enter elements: "<<endl;
    for(int i=1;i<=n;i++)
    {
        cin>>arr[i];
    }
    int limit=n;
    int new_index=n;
    while(limit--)
    {
        int index=1;
        for(int i=2;i<=n;i++)
        {
            index = arr[index]>=arr[i] ? index : i;
        }
        newarr[new_index--]=arr[index];
        arr[index]=INT_MIN;
    }
    cout<<"Sorted Array is: "<<endl;
    for(int i=1;i<=n;i++)
        cout<<newarr[i]<<" ";
    return 0;
}

No comments:

Post a Comment