What is Sorting?

Sorting is a process in which we place the things or numbers in ascending or descending order.

Selection Sort

Selection Sort is an easy and sequential way to sort your data. In selection sorting we pick the first value in the array and compare it with all other values of the array. Program to Sort your data/numbers through Selection Sorting is as below:


void selectionSort(int arr[],int size)
{
  for(int i=0;i<size;i++)
    for(int j=i+1;j<size;j++) if(arr[i]>arr[j])
      {
        int temp=arr[i];
        arr[i]=arr[j];
        arr[j]=temp;
      }
}

The first “for” loop in the above program will decide which value we choose to sort. The second “for” loop is used t

o compare the chosen value with the values which are next to it. The “if” condition decide whether it is to be ascending or descending sorted. When the “if” condition will be true the values will be swapped.

Lets take a look How it Works.

92041

The above array is in unsorted form.

For the first cycle of loop 9 will be compared with all the data in array and swapped with the smallest value which is in this case is 0.

92041

 

02941

Next time 2 will be selected and will be swapped by next smallest value that is 1.

01942

Same with the other values.

01249

Finaly data will be sorted and will be at their sorted position.