From 6a6afd0ebda521010785f2688c5df3eb5a3dd375 Mon Sep 17 00:00:00 2001 From: 101zh <67253838+101zh@users.noreply.github.com> Date: Tue, 9 Jan 2024 21:44:06 +0000 Subject: [PATCH] fix(7.5): i reaches 2nd-to-last index of Array/ArrayList - i (the current index) for selection sort doesn't need to reach the last index of the array --- src/main/java/Unit7/U7_L5_Activity_One.java | 2 +- src/main/java/Unit7/U7_L5_Activity_Two.java | 26 ++++++++++----------- 2 files changed, 13 insertions(+), 15 deletions(-) diff --git a/src/main/java/Unit7/U7_L5_Activity_One.java b/src/main/java/Unit7/U7_L5_Activity_One.java index ec6a0a0..9f8c834 100644 --- a/src/main/java/Unit7/U7_L5_Activity_One.java +++ b/src/main/java/Unit7/U7_L5_Activity_One.java @@ -4,7 +4,7 @@ public class U7_L5_Activity_One { public static void sortAndPrintReverse(String[] arr) { - for (int i = 0; i < arr.length; i++) { + for (int i = 0; i < arr.length - 1; i++) { int high = i; for (int j = i + 1; j < arr.length; j++) { if (arr[j].compareTo(arr[high]) > 0) { diff --git a/src/main/java/Unit7/U7_L5_Activity_Two.java b/src/main/java/Unit7/U7_L5_Activity_Two.java index 583a88d..e930ad1 100644 --- a/src/main/java/Unit7/U7_L5_Activity_Two.java +++ b/src/main/java/Unit7/U7_L5_Activity_Two.java @@ -4,27 +4,25 @@ import java.util.ArrayList; -public class U7_L5_Activity_Two -{ - - public static void selectSortReverse(ArrayList list){ - - for(int i=0; ilist.get(largestIndex)){ - largestIndex=j; +public class U7_L5_Activity_Two { + + public static void selectSortReverse(ArrayList list) { + + for (int i = 0; i < list.size() - 1; i++) { + int largestIndex = i; + for (int j = i + 1; j < list.size(); j++) { + if (list.get(j) > list.get(largestIndex)) { + largestIndex = j; } } int temp = list.get(i); - + list.set(i, list.get(largestIndex)); list.set(largestIndex, temp); } - + System.out.println(list); - + } } -