#Increment counters at the wrong spot

1 messages ยท Page 1 of 1 (latest)

sacred pebbleBOT
#

<@&987246399047479336> please have a look, thanks.

#

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

#
TJ-Bot
For my comp sci course I need to make a program that generates a random number array of either 10, 100, 1000, 5000, or 10000 numbers, lets the user pick if they want the numbers in ascending or descending order, and output them as well as the efficiency in

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?

normal sluice
#

have you tried stepping through your code with a debugger? @magic root

sick ledge
#

It runs through your code step by step and shows you the current values of your variables at each step