google search

Popular Posts


Welcome to BCA Notes

>>>>>>>>>>>>>>>>

Visitors

Search This Blog

Blogger templates

Visitor Map


Thursday 21 August 2014

Selection Sort Algorithm

#include<conio.h>
#include<iostream.h>
#include<stdio.h>

class List
{
public:
// Array of integers to hold values
int arr[20];

// Number of elements in array
int n;

// Function to accept array elements

void read()
{
while (1)
{

cout<<"\nEnter the number of elements in the array: ";
cin>>n;

if (n <= 20)
break;
else
cout << "\nArray can have maximum 20 elements\n";
}

//Display the header

cout<<"\n";
cout<< "-----------------------\n";
cout<< "Enter array elements  \n";
cout<<"-----------------------\n";

// Get array elements
for( int i = 0; i < n; i++ )
{
cout<<"<"<<i+1<<"> ";
cin>>arr[i];

}
}

//Function to swaps the element at index x with the element at index y

void swap(int x, int y)
{
int temp;

temp = arr[x];
arr[x] = arr[y];
arr[y] = temp;

}

void SelectionSortArray()
{
for (int i= 0; i<n-1; i++) //For n-1 passes
{
//Find the minimum value from arr[i] to arr[n-1]

int min = i; //Suppose minimum value is at index i

//Compare all values from index i+1 to index n-1 with
//the value at index min to determine the minimum value.

for (int j=i+1; j<n; j++)
{
if (arr[j] < arr[min])
{
min = j;//Store the index of smaller value in min
}
}

//Swap the value at index i with the value at index j
//to store the minimum value at index i.

swap (i,min);
}
}

void display()
{
cout<<endl;
cout<<"-----------------------\n";
cout<<" Sorted array elements \n";
cout<<"-----------------------\n";

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


int main()
{
// Instantiate an instance of the class
// clrscr();
List myList;

// Accept array elements
myList.read();

// Sort the array
myList.SelectionSortArray();

// Display sorted array
myList.display();

cout<<endl<< "Press Return to exit.";
getch();

}

0 comments:

Post a Comment