CodesJava

Easy learning with example program codes

Java selection sort algorithm example

Selection sort

The algorithm divides the input list into two parts: the sublist of items already sorted, which is built up from left to right at the front (left) of the list, and the sublist of items remaining to be sorted that occupy the rest of the list. Initially, the sorted sublist is empty and the unsorted sublist is the entire input list. The algorithm proceeds by finding the smallest (or largest, depending on sorting order) element in the unsorted sublist, exchanging (swapping) it with the leftmost unsorted element (putting it in sorted order), and moving the sublist boundaries one element to the right.

Selection sort Step-by-step example

Sorted sublist == ( )
Unsorted sublist == (11, 25, 12, 22, 64)
Least element in unsorted list == 11

Sorted sublist ==  (11)
Unsorted sublist == (25, 12, 22, 64)
Least element in unsorted list == 12

Sorted sublist == (11, 12)
Unsorted sublist == (25, 22, 64)
Least element in unsorted list == 22

Sorted sublist == (11, 12, 22)
Unsorted sublist == (25, 64)
Least element in unsorted list == 25

Sorted sublist == (11, 12, 22, 25)
Unsorted sublist == (64)
Least element in unsorted list == 64

Sorted sublist == (11, 12, 22, 25, 64)
Unsorted sublist == ( )

Nothing appears changed on these last two lines because the last two numbers were already in order.

Selection sort can also be used on list structures that make add and remove efficient, such as a linked list. In this case it is more common to remove the minimum element from the remainder of the list, and then insert it at the end of the values sorted so far.

Example:

64 25 12 22 11

11 64 25 12 22

11 12 64 25 22

11 12 22 64 25

11 12 22 25 64

Example

package com.codesjava;
 
public class Test {
       public static int[] selectionSort(int data[]) {
	for (int i = 0; i < data.length - 1; i++) {
            int index = i;
            for (int j = i + 1; j < data.length; j++)
                if (data[j] < data[index]) 
                    index = j;
 
            int smallerNumber = data[index];  
            data[index] = data[i];
            data[i] = smallerNumber;
        }
        return data;
      }
 
      private static void printNumbers(int[] data) {          
        for (int i = 0; i < data.length; i++) {
            System.out.print(data[i]);
            if(i != data.length-1){
            	System.out.print(", ");
            }
        }
        System.out.println("\n");
      }
 
	public static void main(String args[]){
		int[] data = {11, 25, 12, 22, 64}; 
		//Print array elements
		printNumbers(data);
		int[] sortedDate = selectionSort(data);  
		//Print sorted array elements
		printNumbers(sortedDate);
	}
}

Output

11, 25, 12, 22, 64
 
11, 12, 22, 25, 64
Please follow and like us:
error








Copyright © 2019 CodesJava DMCA.com Protection Status