Java Interview Questions - Sort a given Array using Selection Sort (2023) | JavaStructures

Java Interview Questions - Sort a given Array using Selection Sort

In each iteration we select one element and compare it all other elements of the array to find the smallest element
Selection Sort Tutorial
So in the first iteration we get the smallest element and place it in first position . In second iteration we get the second smallest element and place it in second position and so on till the entire array is sorted The complexity of this algorithm is
  • Worst case performance : O(N^2)
  • Best case performance : O(N^2)
  • Average case performance : O(N^2)
package com.javastructures;

public class SelectionSort {
	public static void sort(int arr[]) {
		int i, j, temp;
		for (i = 0; i < arr.length; i++) {
			for (j = i + 1; j < arr.length; j++) {
				if (arr[i] > arr[j]) {
					temp = arr[i];
					arr[i] = arr[j];
					arr[j] = temp;
				}

			}
			display(arr);
		}
	}

	public static void main(String[] args) {

		int arr[] = { 3,7,4,1,9,5,2,8,6};
		sort(arr);
	}

	private static void display(int arr[]) {
		int i;
		for (i = 0; i < arr.length; i++)
			System.out.print(arr[i] + " ");
		    System.out.println();
	}

}