Java program to implement selection sort


Selection sort is a simple sorting algorithm. This sorting algorithm is an in-place comparison-based algorithm in which the list is divided into two parts, the sorted part at the left end and the unsorted part at the right end. Initially, the sorted part is empty and the unsorted part is the entire list.

The smallest element is selected from the unsorted array and swapped with the leftmost element, and that element becomes a part of the sorted array. This process continues moving unsorted array boundary from one element to the right.

Algorithm

1.Set MIN to location 0
2.Search the minimum element in the list
3.Swap with value at location MIN
4.Increment MIN to point to next element
5.Repeat until the list is sorted

Example

Live Demo

public class SelectionSort {
   public static void main(String args[]){
      int array[] = {10, 20, 25, 63, 96, 57};
      int size = array.length;

      for (int i = 0 ;i< size-1; i++){
         int min = i;

         for (int j = i+1; j<size; j++){
            if (array[j] < array[min]){
            min = j;
            }
         }
         int temp = array[min];
         array[min] = array[i];
         array[i] = temp;
      }

      for (int i = 0 ;i< size; i++){
         System.out.print(" "+array[i]);
      }
   }  
}


Updated on: 13-Mar-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements