'F' → Fullscreen
// Figure 1 — Selection Sortpublic static void selectionSort(int[] arr){ for (int i = 0; i < arr.length - 1; i++) { int minIndex = i;
for (int j = i + 1; j < arr.length; j++) { if (arr[j] < arr[minIndex]) { minIndex = j; } }
int temp = arr[i]; arr[i] = arr[minIndex]; arr[minIndex] = temp; }}// Figure 2 — Insertion Sortpublic static void insertionSort(int[] arr){ for (int i = 1; i < arr.length; i++) { int key = arr[i]; int j = i;
while (j > 0 && key < arr[j - 1]) { arr[j] = arr[j - 1]; j--; }
arr[j] = key; }}public class Program{ public static void main(String[] args) { // Task 1 — Trace Selection Sort // // Trace the array after each outer loop pass. // Use this array: // // {7, 3, 8, 1}
int[] nums = {7, 3, 8, 1};
selectionSort(nums);
printArray(nums); }
public static void selectionSort(int[] arr) { for (int i = 0; i < arr.length - 1; i++) { int minIndex = i;
for (int j = i + 1; j < arr.length; j++) { if (arr[j] < arr[minIndex]) { minIndex = j; } }
int temp = arr[i]; arr[i] = arr[minIndex]; arr[minIndex] = temp;
// Add a print here to observe progress } }
public static void printArray(int[] arr) { for (int v : arr) { System.out.print(v + " "); } System.out.println(); }}public class Program{ public static void main(String[] args) { // Task 2 — Implement Insertion Sort // // 1) Copy insertionSort from the figure. // 2) Test on {5, 2, 9, 1, 7} // 3) Print before and after.
int[] nums = {5, 2, 9, 1, 7};
System.out.println("Before:"); printArray(nums);
insertionSort(nums);
System.out.println("After:"); printArray(nums); }
public static void insertionSort(int[] arr) { for (int i = 1; i < arr.length; i++) { int key = arr[i]; int j = i;
while (j > 0 && key < arr[j - 1]) { arr[j] = arr[j - 1]; j--; }
arr[j] = key; } }
public static void printArray(int[] arr) { for (int v : arr) { System.out.print(v + " "); } System.out.println(); }}import java.util.Arrays;
public class Program{ public static void main(String[] args) { // Task 3 — Compare with Arrays.sort // // 1) Create an array. // 2) Copy it. // 3) Sort one using selectionSort. // 4) Sort the other using Arrays.sort. // 5) Compare results.
int[] nums = {10, 4, 7, 2, 9};
int[] copy = Arrays.copyOf(nums, nums.length);
selectionSort(nums); Arrays.sort(copy);
System.out.println("Selection sort result:"); printArray(nums);
System.out.println("Arrays.sort result:"); printArray(copy); }
public static void selectionSort(int[] arr) { for (int i = 0; i < arr.length - 1; i++) { int minIndex = i;
for (int j = i + 1; j < arr.length; j++) { if (arr[j] < arr[minIndex]) { minIndex = j; } }
int temp = arr[i]; arr[i] = arr[minIndex]; arr[minIndex] = temp; } }
public static void printArray(int[] arr) { for (int v : arr) { System.out.print(v + " "); } System.out.println(); }}Before:5 2 9 1 7After:1 2 5 7 9
Selection sort result:2 4 7 9 10Arrays.sort result:2 4 7 9 10Submit your completed activity.