Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions java/SelectionSort.java
Original file line number Diff line number Diff line change
@@ -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;
}
}