-
Notifications
You must be signed in to change notification settings - Fork 864
Open
Description
The instructions say: “Implement the method in a way that takes at most list1.length + list2.length comparisons”, but your sort takes many more than that.
Count the number of comparisons in the sort
public static void sort(int[] list) {
int nCompare = 0;
for (int i = 0; i < list.length - 1; i++) {
int min = list[i];
int minIndex = i;
for (int j = i + 1; j < list.length; j++) {
nCompare++;
if (list[j] < min) {
min = list[j];
minIndex = j;
}
}
if (minIndex != i) {
list[minIndex] = list[i];
list[i] = min;
}
}
System.out.println("Total compares: " + nCompare);
}
}
For arrays [10, 20, 30, 40, 50] and [1, 2, 3, 4, 5] in that order, it takes 45 comparisons, which is far more than the 10 that the exercise allows.
(By the way, several students in my class copied this wrong solution and lost a large number of points for doing it incorrectly -- and for plagiarism.)
Metadata
Metadata
Assignees
Labels
No labels