Saturday, June 13, 2015

C++ program to implement selection Sort

/*-------------------------------------------------------------------------------------------------------------
File Name:      selection.cpp
Author:           sujith
Program:        Write a C++ program to implement selection Sort
Date:               23-04-2015
--------------------------------------------------------------------------------------------------------------*/
#include<iostream>
#include<stdio.h>
using namespace std;
void selectionsort(int a[],int n);
int main()
{
         int i,n,a[20];
        cout<<"Enter the total number of element\n";
        cin>>n;
        cout<<"Enter the Elements\n";
        for(i=0;i<n;i++)
        {
                cin>>a[i];
        }
        cout<<"After sorting\n";
        selectionsort(a,n);
        for(i=0;i<n;i++){
        cout<<a[i]<<"\n";
        }
}
void selectionsort(int a[],int n)
{
        int i,j,max,index;

        for(i=n-1;i>=0;i--){
                max=a[0];
                index=0;
                for(j=1;j<=i;j++){
                        if(a[j]>max){
                                max=a[j];
                                index=j;
                        }
                }
                a[index]=a[i];
                a[i]=max;
        }
}




OUTPUT:

[141740@localhost ~]$ g++ selection.cpp
[141740@localhost ~]$ ./a.out
Enter the total number of element
5
Enter the Elements
15        2          4          89        66
After sorting
2
4
15
66
89
[141740@localhost ~]$ g++ selection.cpp
[141740@localhost ~]$ ./a.out
Enter the total number of element
6
Enter the Elements
1          5          4          99        6          3
After sorting
1
3
4
5
6
99
[141740@localhost ~]$





No comments:

Post a Comment