In this tutorial we will see that how to implement selection sort algorithm in java. The selection sort is a combination of searching and sorting. During each pass, the unsorted element with the smallest or largest value is moved to its proper position in the array. The number of times the sort passes through the array is one less than the number of items in the array. In the selection sort, the inner loop finds the next smallest or largest value and the outer loop places that value into its proper location.

implement selection sort algorithm in java example:-

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | public class SelectionSort { public static void sort( int arr[] ){ int i, j, pos, temp; int arrLength = arr.length; for (i = 0; i < arrLength-1; i++) { pos = i; for (j = i+1; j < arrLength; j++) { if (arr[j] < arr[pos]) { pos = j; } } temp = arr[i]; arr[i] = arr[pos]; arr[pos]= temp; } } public static void main(String[] args) { int[] arr1 = {-6,10,34,2,56,7,67,88,42,0}; System.out.println("array before sorting \n"); for(int i:arr1){ System.out.print(i); System.out.print(", "); } System.out.println("\n\n array after sorting \n"); sort(arr1); for(int i:arr1){ System.out.print(i); System.out.print(", "); } } } |

output:-

selection sort has O(n2) time complexity which makes it inefficient on large lists. Selection sort is known for its simplicity, and it has performance advantages over more complicated algorithms in certain situations, specially where auxiliary memory is limited. the Worst case performance of selection sort is О(n2), Best case performance is O(n2) and Average case performance is О(n2)