From 37ef78ca96a21784b6d87cab958ed34dfa622148 Mon Sep 17 00:00:00 2001 From: HetuKariya <131229641+HetuKariya@users.noreply.github.com> Date: Sat, 4 Oct 2025 14:00:14 +0530 Subject: [PATCH] Added SelectionSort.java --- java/SelectionSort.java | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 java/SelectionSort.java diff --git a/java/SelectionSort.java b/java/SelectionSort.java new file mode 100644 index 0000000..fd7ede0 --- /dev/null +++ b/java/SelectionSort.java @@ -0,0 +1,37 @@ +import java.util.*; + +public class SelectionSort { + public static void main(String[] args) { + Scanner scan = new Scanner(System.in); + int n = scan.nextInt(); + int[] arr = new int[n]; + for(int i = 0; i < n; i++) + arr[i] = scan.nextInt(); + selectionSort(arr); + System.out.println(Arrays.toString(arr)); + } + + public static void selectionSort(int[] arr) { + for(int i = 0; i < arr.length; i++) { + // find the max item in the remaining array and swap with the correct index + int last = arr.length - i - 1; + int maxIndex = getMaxIndex(arr, 0, last); + swap(arr, maxIndex, last); + } + } + + public static int getMaxIndex(int[] arr, int start, int end) { + int max = start; + for(int i = start; i <= end; i++) { + if(arr[i] > arr[max]) + max = i; + } + return max; + } + + public static void swap(int[] arr, int i, int correct) { + int temp = arr[i]; + arr[i] = arr[correct]; + arr[correct] = temp; + } +} \ No newline at end of file