We help IT Professionals succeed at work.

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

15jen
15jen asked
on
Medium Priority
270 Views
Last Modified: 2013-12-29
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;
Comment
Watch Question

CERTIFIED EXPERT
Top Expert 2016
Commented:
>>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

Not the solution you were looking for? Getting a personalized solution is easy.

Ask the Experts
Java Developer
CERTIFIED EXPERT
Top Expert 2010
Commented:
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;

CERTIFIED EXPERT
Top Expert 2016

Commented:
15jen, i'm interested to know why you accepted that answer - why would you want a hard-coded println in a sort method?
Access more of Experts Exchange with a free account
Thanks for using Experts Exchange.

Create a free account to continue.

Limited access with a free account allows you to:

  • View three pieces of content (articles, solutions, posts, and videos)
  • Ask the experts questions (counted toward content limit)
  • Customize your dashboard and profile

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.