HW
import java.util.Arrays;
public class Sort {
public static void main(String[] args) {
// test array
int[] supplies = {29, 10, 14, 37, 13, 18, 25, 30, 4, 9, 12, 40, 50, 23, 28};
// insertion sort
insertionSort(supplies);
// reset array for selection sort
supplies = new int[]{29, 10, 14, 37, 13, 18, 25, 30, 4, 9, 12, 40, 50, 23, 28};
// selection sort
selectionSort(supplies);
}
public static void insertionSort(int[] arr) {
for (int i = 1; i < arr.length; i++) {
int current = arr[i];
int j = i - 1;
// shift larger elements to the right
while (j >= 0 && arr[j] > current) {
arr[j + 1] = arr[j];
j--;
}
// place the current value in the correct position
arr[j + 1] = current;
}
System.out.println("insertion sort: " + Arrays.toString(arr));
}
public static void selectionSort(int[] arr) {
for (int current = 0; current < arr.length - 1; current++) {
int min = current;
for (int i = current + 1; i < arr.length; i++) {
if (arr[i] < arr[min]) {
min = i;
}
}
int temp = arr[current];
arr[current] = arr[min];
arr[min] = temp;
}
System.out.println("selection sort: " + Arrays.toString(arr));
}
}
Sort.main(null);
insertion sort: [4, 9, 10, 12, 13, 14, 18, 23, 25, 28, 29, 30, 37, 40, 50]
selection sort: [4, 9, 10, 12, 13, 14, 18, 23, 25, 28, 29, 30, 37, 40, 50]