Selection Sort

PSeudoCode:

selectionSort(A,n)
{
    for(i=0 to n-1)
    {
        min=i;
        for(j=i+1 to n){
            if(arr[j]<arr[min]){
                min=j;
            }
        }
        if(min!=i)
        {
            swap(arr[min],arr[i]);
        }
    }

}

Implemented Code:

#include<bits/stdc++.h>
using namespace std;
int swaps(int *p,int *q)
{
    int temp=*q;
    *q=*p;
    *p=temp;
}

void selectionSort(int *arr,int n)
{
    int i,j,mins;
    for(i=0; i<n-1; i++)
    {
        mins=i;
        for(j=i+1; j<n; j++)
        {
            if(arr[j]<arr[mins])
            {
                mins=j;
            }
        }
        if(mins!=i){
        swaps(&arr[mins],&arr[i]);
        }
    }
}
printArray(int *arr,int n)
{

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

}

int main()
{
    //int A[]= {4,42,23,16,8,15};
    int A[]= {2,7,4,1,5,3};
    int sizes=sizeof(A)/sizeof(A[0]);
    //selectionSort(A,6);
    selectionSort(A,sizes);
    printArray(A,sizes);

    return 0;
}

output:

//4 8 15 16 23 42
1 2 3 4 5 7

 

It would be a great help, if you support by sharing :)
Author: zakilive

Leave a Reply

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