How do I make a method to count swaps in my code and then display them?

Here are the swaps++>>>>>>>>>>>
public int insertionsort(int elements) {
                  int inside, outside, swaps = 0;
                  for (outside = 1; outside < elements; outside++) {
                        int temp = randomnumbers[outside];
                        inside = outside;
                        while ((inside > 0) && (randomnumbers[inside - 1] >= temp)) {
                              randomnumbers[inside] = randomnumbers[inside - 1];
                              --inside;
                              swaps++;
                        }
                        randomnumbers[inside] = temp;
                  }
                  return swaps;
15jenAsked:
Who is Participating?
 
objectsCommented:
public int insertionsort(int elements) {
                  int inside, outside, swaps = 0;
                  for (outside = 1; outside < elements; outside++) {
                        int temp = randomnumbers[outside];
                        inside = outside;
                        while ((inside > 0) && (randomnumbers[inside - 1] >= temp)) {
                              randomnumbers[inside] = randomnumbers[inside - 1];
                              --inside;
                              swaps++;
                        }
                        randomnumbers[inside] = temp;
                  }
                  System.out.println("Number of swaps = "+swaps);
                  return swaps;

0
 
CEHJCommented:
>>return swaps;

You are already counting the swaps. So you only need to do something like
System.out.printf("The code performed %d swap(s)\n", insertionsort(5));

Open in new window

0
 
CEHJCommented:
15jen, i'm interested to know why you accepted that answer - why would you want a hard-coded println in a sort method?
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.