AP Computer Science Exam Question:
Consider the following code snippet that implements the Insertion Sort algorithm in Java:
public class InsertionSort {
public static void sort(int[] arr) {
int n = arr.length;
for (int i = 1; i < n; i++) {
int key = arr[i];
int j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}
}
public static void main(String[] args) {
int[] arr = {5, 2, 9, 1, 3};
sort(arr);
for (int num : arr) {
System.out.print(num + " ");
}
}
}
Explain how the Insertion Sort algorithm works and provide a step-by-step breakdown of the sorting process for the given input array [5, 2, 9, 1, 3]. Show the intermediate steps after each iteration of the outer loop.
Answer:
The Insertion Sort algorithm works by dividing the given array into two subarrays: a sorted subarray and an unsorted subarray. The algorithm iterates through the unsorted subarray and repeatedly selects an element, compares it with the elements in the sorted subarray, and inserts it into the correct position in the sorted subarray.
Now, let's step through the sorting process of the input array [5, 2, 9, 1, 3] using the Insertion Sort algorithm:
Iteration 1:
Iteration 2:
Iteration 3:
Iteration 4:
Final Sorted Array: [1, 2, 3, 5, 9]
At the end of the sorting process, the given input array [5, 2, 9, 1, 3] is sorted in ascending order, resulting in the array [1, 2, 3, 5, 9].