'F' → Fullscreen
public class Program{ public static void main(String[] args) { // Task 1 — Review: Min & Max int[] nums = {4, 7, 2, 9, 5};
int min = nums[0]; int max = nums[0];
for (int i = 1; i < nums.length; i++) { if (nums[i] < min) { min = nums[i]; }
if (nums[i] > max) { max = nums[i]; } }
System.out.println("Min: " + min); System.out.println("Max: " + max); }}public class Program{ public static void main(String[] args) { // Task 2 — Swap Algorithm (precursor to sorting) int[] nums = {10, 20, 30, 40};
// 1) Swap index 0 and index 3 int temp = nums[0]; nums[0] = nums[3]; nums[3] = temp;
// 2) Print each element on its own line (use traversal) for (int i = 0; i < nums.length; i++) { System.out.println(nums[i]); }
// 3) Challenge (optional): swap index 1 and index 2, then print again. }}found) and an index (foundIndex). -1 as the “not found” index. public class Program{ public static void main(String[] args) { // Task 3 — Linear Search (AP Required) int[] nums = {4, 7, 2, 9, 5}; int target = 9;
boolean found = false; int foundIndex = -1;
for (int i = 0; i < nums.length; i++) { if (nums[i] == target) { found = true; foundIndex = i; } }
System.out.println("Found: " + found); System.out.println("Index: " + foundIndex); }}low, high, and mid to cut the search space in half. public class Program{ public static void main(String[] args) { // Task 4 — Binary Search (ENRICHMENT / FOR FUN) // Not required for the AP CSA exam int[] nums = {2, 4, 7, 9, 12, 15}; int target = 12;
int low = 0; int high = nums.length - 1;
boolean found = false; int foundIndex = -1;
while (low <= high) { int mid = (low + high) / 2;
if (nums[mid] == target) { found = true; foundIndex = mid; break; } else if (nums[mid] < target) { low = mid + 1; } else { high = mid - 1; } }
System.out.println("Found: " + found); System.out.println("Index: " + foundIndex); }}Your program output should something similar to the sample output below.
Min: 2Max: 940203010Found: trueIndex: 3Found: trueIndex: 4You may write your reflection answers as comments at the bottom of your code.
foundIndex when the target is not found? Why is that useful?Submit your activity and reflection answers to the appropriate dropbox.