Selection Sort

It is a type of sorting technique where the smallest or largest element is selected from an unsorted part of the array and sent to the sorted one.  The smallest or largest element is selected and swapped with the first element of the unsorted array. Well, this depends on the algorithm we are using.

Sorting in Ascending Order:

Here, the array will have a set of integer values. We need to sort the array in ascending order i.e. the smallest element will be present at the beginning of the array and the largest element will be present at the end.

Algorithm:

  1. A loop will start where smallestUnsortedIndex = 0; smallestUnsortedIndex< array.length-1; smallestUnsortedIndex++ (Note: Here smallestUnsortedIndex limits to the array.length-1 because it will only be able to reach the second last element. Last element will already be at its correct position.)
  2. Each time we are searching for the index which has the smallest element in the unsorted array, we consider the initial value of indexWithSmallestElement = smallestUnsortedIndex. This is considered in order to select the first element of the unsorted array as a reference for comparing with the rest of the elements of the unsorted array.
  3. Once the indexWithSmallestElement is found, we need to swap the smallestElement with the smallestUnsortedIndex.
  4. Steps 2 and 3 are continued till the array is sorted.

Java:

public class Main {
    public static void main(String[] args){
        int[] a = {7,6,2,1,2,3,};
        int smallestUnsortedIndex;
        int smallestIndex;
        for(smallestUnsortedIndex=0;smallestUnsortedIndex<a.length-1;smallestUnsortedIndex++)
        {
            smallestIndex=smallestUnsortedIndex;
            for(int i=smallestUnsortedIndex+1;i<a.length;i++)
            {
                if(a[smallestIndex]>a[i])
                    smallestIndex=i;
            }
            int temp = a[smallestUnsortedIndex];
            a[smallestUnsortedIndex]=a[smallestIndex];
            a[smallestIndex]=temp;
        }
        for(int i = 0;i<a.length;i++)
        {
            System.out.print(a[i]+" ");
        }
    }
}

No comments

Theme images by Flashworks. Powered by Blogger.