Sitelet https://java2blog.com/selection-sort-in-java/

Selection sort in java

If you want to practice data structure and algorithm programs, you can go through data structure and algorithm interview programs.

Selection sort is an in place comparison sorting algorithm. It is very simple to implement but it does not go well with large number of inputs.
[toc]

Selection sort algorithm

  • Find the minimum element in the list.
  • Swap minimum element with current element.
  • Repeat the whole process until array is fully sorted.
Below visualization will make it more clear

Selection sort algorithm

package org.arpit.java2blog;

import java.util.Arrays;

public class SelectionSortMain {

 public static int[] selectionSort(int[] arr){

 for (int i = 0; i < arr.length - 1; i++)
 {
 int index = i;
 for (int j = i + 1; j < arr.length; j++)
 if (arr[j] < arr[index])
 index = j;

 int smallerNumber = arr[index];
 arr[index] = arr[i];
 arr[i] = smallerNumber;
 }
 return arr;
 }

 public static void main(String a[]){

 int[] arr = {40,10,-30,45,39,32};
 System.out.println("Before Sorting : ");
 System.out.println(Arrays.toString(arr));
 arr = selectionSort(arr);
 System.out.println("===================");
 System.out.println("After Sorting : ");
 System.out.println(Arrays.toString(arr));
 }
}

When you run above program, you will get below output:

Before Sorting :
[40, 10, -30, 45, 39, 32]
===================
After Sorting :
[-30, 10, 32, 39, 40, 45]

Time complexity

Best case : O(N^2)
Average case : O(N^2)
Worst case : O(N^2)

To understand more about complexity,please go through complexity of algorithm.
[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.