codescracker


c++

C++ Program Selection Sort



« Previous Program Next Program »


Selection Sort in C++

To sort an array in ascending order using selection sort technique in C++ programming, then you have to ask to the user to enter the array size and array elements, now start comparing the array elements and start placing the smaller elements before bigger to arrange all the array elements in ascending order. Here, we use swapping of the elements with the help of a variable say temp of same type. That is, on found (bigger element before smaller element), start swapping with temp variable, place the first number (bigger) in the temp and second number (smaller) in the first (bigger), then temp in the second number (bigger). Now at the place of bigger element, you have a smaller element and at the place of smaller element, you have a bigger element. After performing this, continue to next match to sort the whole array in ascending order.

C++ Programming Code for Selection Sort

Following C++ program ask to the user to enter array size and array element, then it will sort the array is ascending order and display the sorted array:

/* C++ Program - Selection Sort */
		
#include<iostream.h>
#include<conio.h>
void main()
{
	clrscr();
	int size, arr[50], i, j, temp;
	cout<<"Enter Array Size : ";
	cin>>size;
	cout<<"Enter Array Elements : ";
	for(i=0; i<size; i++)
	{
		cin>>arr[i];
	}
	cout<<"Sorting array using selection sort...\n";
	for(i=0; i<size; i++)
	{
		for(j=i+1; j<size; j++)
		{
			if(arr[i]>arr[j])
			{
				temp=arr[i];
				arr[i]=arr[j];
				arr[j]=temp;
			}
		}
	}
	cout<<"Now the Array after sorting is :\n";
	for(i=0; i<size; i++)
	{
		cout<<arr[i]<<" ";
	}
	getch();
}

When the above C++ program is compile and executed, it will produce the following result:

selection sort in C++ Programming

Same Program in Other Language

You may like the same program in other programming languages:


« Previous Program Next Program »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test