Sorting structure using selection sort in c++

Sorting structure using selection sort method is one such problem that every class 12 student must try. It will help them to concrete their concepts of sorting algorithm.

Students of class 11 and 12 may understand how to sort a structure using selection sort although students generally knew simple array sorting but with the help of this example they will be able to sort a structure.

According to CBSE class 11 and 12 syllabus three sorting are introduced Bubble,Insertion and selection sort. Students can simply download it and copy and paste in C++ editor and can see the actual method of selection sort using a structure .

A little introduction to selection sort algorithm

In selection sort algorithm, first element of an array is compared with all the remaining element of that array, this way we find out the lowest element and its position. Now this lowest number is swapped with the first element of that array. This way we are able to obtain the lowest element at the top position.

Now, leave first number and start the whole process again from the second position- Consider this element as the lowest element and repeat the process to find out another lowest number in the list. swap this newly selected lowest number from second position element.

This way we are able to find out two element in arranged format. Now repeat the same process in this whole array.

Here is a sample program to demonstrate the use of selection sort method of an array of structure

struct stud
      char name[20];
      int rn;
void main() {
 stud s[5]={{"Anil",45},{"Bablu",87},{"Jugnu",77},{"Harees",11},{"Chayan",10}};
 stud T;
 int t,min,p;
	for(int i=0;i<5;i++){
	     for(int j=i+1;j<5;j++){
		     min=s[j].rn; p=j;}
              } //end of inner for loop
              //swap elements
   //output phase  
  for(int q=0;q<5;q++) {
    cout<<s[q].rn<<"   "<<s[q].name<<endl;

NOTE : The above program was written using Borland Turbo C++ compiler.Now concentrate on the following line


Since all the elements belongs to same data structure we can rewrite

 T = S[P];

Suggested Reading

If you have an issue while compiling this program to debugging this program. Please feel free to contact us.

Print Friendly, PDF & Email

Related Posts

If you like CBSEToaday and would like to contribute, you can also write an article using submit article or mail your article to See your article appearing on the main page and help other students/teachers.