The selection sorting algorithm is one of the simplest sorting algorithms: it divides input into two parts and builds a sorted part from the left as it passes through the unsorted part of the array. With each iteration sorted part increases, while the unsorted part decreases by one element.
Selection sort is an in-place comparison based sorting algorithm. Its time complexity is O(n2), while it is space complexity is O(n).
Please see below the implementation in Java:
import java.util.Arrays;
public class SelectionSort {
public static void main(String []args){
char[] arr = {'H','S','A','F','R','P','E','C','Z','W','G','J','B','Q','L'};
System.out.println("Input array: " + Arrays.toString(arr));
sort(arr, arr.length);
System.out.println("Sorted array: " + Arrays.toString(arr));
}
private static void sort(char arr[], int n) {
if (n > arr.length) {
n = arr.length;
}
for (int i = 0; i < n-1; i++) {
int min_index = i;
for (int j = i+1; j < n; j++) {
if (arr[j] < arr[min_index]) {
min_index = j;
}
}
char temp = arr[min_index];
arr[min_index] = arr[i];
arr[i] = temp;
}
}
}
The output of the application:
Input array: [H, S, A, F, R, P, E, C, Z, W, G, J, B, Q, L]
Sorted array: [A, B, C, E, F, G, H, J, L, P, Q, R, S, W, Z]
Ashley P.
Could you tell me why you used a private class particularly? Can I instated use a public class? And the question says to write a function in the form selectionsort(Arr, N). But java won't let you use that exact format for parameters where we define the method. Instead is it incorrect if I define parameters the way you've defined it?05/12/20