CARVIEW |
Select Language
HTTP/2 200
cache-control: public, max-age=300, stale-while-revalidate=604800
referrer-policy: strict-origin-when-cross-origin
x-app-version: v251008-h-251010-1202
x-content-type-options: nosniff
x-frame-options: SAMEORIGIN
x-xss-protection: 1; mode=block
x-app-type: Learn
x-middleware-rewrite: /answers/howdev/how-to-implement-selection-sort-in-java
x-nextjs-cache: HIT
etag: W/"zpl0apuectj7mr"
content-type: text/html; charset=utf-8
x-cloud-trace-context: a73db6268ed0f5c04086830e75539478;o=1
date: Sun, 12 Oct 2025 06:43:48 GMT
server: Google Frontend
via: 1.1 google
vary: Accept-Encoding
content-encoding: gzip
x-cache-status: miss
alt-svc: h3=":443"; ma=2592000,h3-29=":443"; ma=2592000
How to implement Selection sort in Java 



How to implement Selection sort in Java
Selection sort is an in-place sorting algorithm; it does not require any extra space apart from the given array. The array will be divided into two parts: sorted and unsorted.
In our example, the sorted part comes before the unsorted part; however, it may be the opposite with some slight changes.
The algorithm works as follows:
- Initially, the whole array is unsorted.
- Find the minimum of the unsorted part and swap it with the first element.
- Now, consider the minimum number chosen in the previous step as part of the sorted array. The size of the sorted part grows this way.
- Continue steps one through three until there are no elements left in the un-sorted part.
Given an array, we need to sort it using Selection sort. Hence, we must select the smallest element in the array.
1 of 8
In every iteration, the minimum element of the unsorted part (orange) is swapped with the first element of the un-sorted array (green).
1 of 8
The element becomes part of the sorted array.
1 of 8
Same process of finding the minimum and swapping it continues.
1 of 8
1 of 8
Implementation
class SelectionSort {public static void main(String[] args){SelectionSort ss = new SelectionSort();int[] arr = {2,1,0,8,-4};System.out.println("Original Array:");ss.printArr(arr);arr = ss.sort(arr);System.out.println("\nSorted Array:");ss.printArr(arr);}int[] sort(int[] arr){int min, minIndex, temp;// 'start' is the point where 'unsorted' array beginsfor(int start = 0; start < arr.length - 1; start++){// Finding the minimummin = arr[start];minIndex = start;for(int i = start + 1; i < arr.length; i++){if(arr[i] < min){min = arr[i];minIndex = i;}}// Swap the minimum with the first elementtemp = min;arr[minIndex] = arr[start];arr[start] = temp;}return arr;}void printArr(int[] arr){for(int i = 0; i < arr.length; i++)System.out.print(arr[i] + " ");}}
Relevant Answers
Explore Courses
Free Resources
Copyright ©2025 Educative, Inc. All rights reserved