# 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

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

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

```T.rn=s[p].rn;
strcpy(T.name,s[p].name);
s[p].rn=s[i].rn;
strcpy(s[p].name,s[i].name);
s[i].rn=T.rn;
strcpy(s[i].name,T.name);
```

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

``` T = S[P];
S[p]=S[i];
S[i]=T
```