#Increment counters at the wrong spot
1 messages ยท Page 1 of 1 (latest)
Here is an AI assisted attempt to answer your question ๐ค. Maybe it helps! In any case, a human is on the way ๐. To continue talking to the AI, you can use </chatgpt:1108714622413963314>.
nt to sort in ascending or descending order, and then sorts the array using either a bubble sort or selection sort.
I am having trouble with my program where I increment my counters for swaps and comparisons at the wrong spot. As a result, my output is incorrect and I can't figure out how to fix it.
Here is a snippet of my code:
int comparisons = 0;
int swaps = 0;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
swaps++;
}
comparisons++;
}
}
System.out.println("Number of comparisons: " + comparisons);
System.out.println("Number of swaps: " + swaps);
I believe the issue lies in where I am incrementing the counters 'comparisons' and 'swaps'. Can someone please help me identify where I should be placing these increments to correctly count the number of comparisons and swaps in my sorting algorithm?
have you tried stepping through your code with a debugger? @magic root
It runs through your code step by step and shows you the current values of your variables at each step