Site icon

Sort an integer array using selection sort algorithm in java (with example)

What is selection sort algorithm?

Algorithm: sort an integer array using selection sort in java

  1. Given an unsorted integer array of length n.
  2. We will use two for loop to sort an input array.
  3. Start iterating through the array
    • Outer for loop will iterate from 0 to n – 1 and let the index will be outerindex.
    • Select current index are as probable minimum element in unsorted array.
    • Start inner for loop from outerindex  + 1 to n.
      • Find minimum element in an array i.e. right side of outerindex + 1.
      • Add minimum element to sorted list.
  4. Once, we are out of loop, we will get the sorted array.

Example- sort integer array using selection sort algorithm in java.

Fig 1 : Given unsorted array
Fig 2: Array after first iteration of selection sort i.e. 7 at its final position
Fig 3: Array after second iteration of selection sort i.e. 9 at its final position
Fig 4: Array after third iteration of selection sort i.e. 10 at its final position
Fig 5: Array after fourth iteration of selection sort i.e. 12 at its final position
Fig 6: Array after fifth iteration of selection sort i.e. 25 at its final position

Performance analysis of selection sort algorithm

S. No.Cases  Complexity
1Best case O(n^2)
2Average case O(n^2)
3Worst case O(n^2)

Program – sort an integer array using selection sort algorithm in java

package org.learn.arrays;

import java.util.Arrays;

public class SelectionSort {

	public static void main(String[] args) {
		
		int[] example1 = { 10, 7, 25, 20, 12, 9 };
		System.out.println("Unsorted array is : "+Arrays.toString(example1));
		selectionSort(example1);
		
		int[] example2 = { 5, 4, 3, 2, 1, 0 };
		System.out.println("\nUnsorted array is : "+Arrays.toString(example2));
		selectionSort(example2);
	}

	private static void selectionSort(int[] arr) {
		int length = arr.length;
		for (int outterIndex = 0; outterIndex < length - 1 ; outterIndex++) {
			//mark current index as minimum value index
			int iCurrentMin = outterIndex;
			for (int innerIndex = iCurrentMin + 1;  innerIndex < length; innerIndex++) { if (arr[iCurrentMin] > arr[innerIndex]) {
					//save the actual min value index
					iCurrentMin = innerIndex;
				}
			}
			//If current element is not smallest, let us swap it
			if(iCurrentMin != outterIndex) {
				swap(arr,iCurrentMin, outterIndex);
			}
		}
		System.out.println("Sorted Array is   : "+ Arrays.toString(arr));
	}

	private static void swap(int[] arr, int index_1, int index_2) {
		int temp = arr[index_1];
		arr[index_1] = arr[index_2];
		arr[index_2] = temp;
	}
}

Output – sort an array using selection sort algorithm in java

Unsorted array is : [10, 7, 25, 20, 12, 9]
Sorted Array is   : [7, 9, 10, 12, 20, 25]

Unsorted array is : [5, 4, 3, 2, 1, 0]
Sorted Array is   : [0, 1, 2, 3, 4, 5]
Exit mobile version