Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Exercise 7_31 is not solved correctly #40

Open
jdeisenberg opened this issue Oct 31, 2019 · 0 comments
Open

Exercise 7_31 is not solved correctly #40

jdeisenberg opened this issue Oct 31, 2019 · 0 comments

Comments

@jdeisenberg
Copy link

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.)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant