# difficulties in passing an array through a method for bubble sorting

Page 1 of 1

## 9 Replies - 1242 Views - Last Post: 23 September 2011 - 02:08 PMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'https://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=248199&amp;s=4bb33f7f1e72000e35d575f38d456873&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 TheMantis

Reputation: 1
• Posts: 11
• Joined: 01-April 11

# difficulties in passing an array through a method for bubble sorting

Posted 22 September 2011 - 12:09 PM

Hey guys, programming noob here looking for some help with a school assignment. Essentially, what I have to do is make a program that takes integers as input, computes the frequency, and then sorts the grades according to how the user chooses to sort them (either ascending or descending). The point of this assignment is to effectively use arrays and switch statements (while also using sorting, I suppose).

Anyways, to begin the assignment I first made it so the program would take the grades as input. Then, I made it so it would display the frequency of each grade as a table. Here is the code for that:
```import java.util.Scanner;
{
public static void main(String[] args)
{
int numTests;
int[] tests;
int freq [];

Scanner input = new Scanner(System.in);
System.out.println("How many test scores would you like to enter? ");
numTests = input.nextInt();
tests = new int[numTests];
freq = new int [101];

for (int index = 0; index < tests.length; index++)
{
System.out.println("Enter test score " + (index + 1) + ": ");
tests[index] = input.nextInt();
++freq[tests[index]];
}
for (int count = 0; count < freq.length; count++)
{
if (freq[count]>0)
{
System.out.println(count +"\t"+freq[count]);
}
}

}
}

```

No problems there. Now, what I'm trying to do is make a switch that asks the user whether or not they would like the grades to display in descending or ascending order. Before making the switch statement, I first wanted to attempt to get the scores to display in descending order, this is where I've been unsuccessful. I'm trying to make a bubble sort method that does this...but I'm having a hard time figuring it out. Here is my unsuccessful attempt:
```import java.util.Scanner;
{
public static void main(String[] args)
{
int numTests;
int[] tests;
int[] freq;

Scanner input = new Scanner(System.in);
System.out.println("How many test scores would you like to enter? ");
numTests = input.nextInt();
tests = new int[numTests];
freq = new int [101];

for (int index = 0; index < tests.length; index++)
{
System.out.println("Enter test score " + (index + 1) + ": ");
tests[index] = input.nextInt();
++freq[tests[index]];
}

for (int count = 0; count < freq.length; count++)
{
bubbleSort(freq, count);
if (freq[count]>0)
{
System.out.println(count +"\t"+freq[count]);
}
}

}
public static void bubbleSort(int[] freq, int length)
{
int temp, counter, index;

for(counter=0; counter<length-1; counter++)
{
for(index=0; index<length-1-counter; index++)
{
if(freq[index] > freq[index+1])
{
temp = freq[index];
freq[index] = freq[index+1];
freq[index+1] = temp;
}
}
}
}
}

```

Obviously my code is erroneous, but I don't know where my errors are or how to rectify them. The program works just the same as it did without any sorting. Any tips? My understanding of methods is not very good yet, and I'm thinking I'm not correctly passing the array to the method.

Is This A Good Question/Topic? 0

## Replies To: difficulties in passing an array through a method for bubble sorting

### #2 creative code monkey

Reputation: 14
• Posts: 45
• Joined: 14-September 11

## Re: difficulties in passing an array through a method for bubble sorting

Posted 22 September 2011 - 12:18 PM

You need to return the frequency array back to the calling program. An int[] isn't by reference, it's by value, so the bubbleSort() method makes it's own local copy of the array, and then just dumps it.

### #3 TheMantis

Reputation: 1
• Posts: 11
• Joined: 01-April 11

## Re: difficulties in passing an array through a method for bubble sorting

Posted 22 September 2011 - 01:20 PM

creative code monkey, on 22 September 2011 - 12:18 PM, said:

You need to return the frequency array back to the calling program. An int[] isn't by reference, it's by value, so the bubbleSort() method makes it's own local copy of the array, and then just dumps it.

Keep in mind, I'm a programming noob...can you elaborate more or perhaps show me an implementation of this?

What I think you're telling me, is that the parameters for my bubbleSort() method has no value and that I need to use a return statement in my main method to correct this. Is this correct?

### #4 blackcompe

• D.I.C Lover

Reputation: 1159
• Posts: 2,547
• Joined: 05-May 05

## Re: difficulties in passing an array through a method for bubble sorting

Posted 22 September 2011 - 01:29 PM

Quote

You need to return the frequency array back to the calling program. An int[] isn't by reference, it's by value, so the bubbleSort() method makes it's own local copy of the array, and then just dumps it.

Java is pass by value, but when you pass an object, it's effectively pass-by-reference: changes to the object will be reflected in the calling method. When you pass a reference in Java, it's like passing a pointer in C.

```Obviously my code is erroneous, but I don't know where my errors are or how to rectify them. The program works just the same as it did without any sorting. Any tips? My understanding of methods is not very good yet, and I'm thinking I'm not correctly passing the array to the method.

```

I don't see how this is erroneous. It works just fine. The question is what exactly are you looking to do?

```System.out.println( "\nGrade\tFrequency" );
for ( int count = 0; count < freq.length; count++ ) {
//bubbleSort( freq, count );
if ( freq[ count ] > 0 ) {
System.out.println( count + "\t" + freq[ count ] );
}
}

```

Obviously, that loop will print the scores in ascending order, because your traversing the frequency array in ascending order, and it's elements are sorted already, since you said:

```++freq[tests[index]];
```

If you want to show them in the order they were input:

```System.out.println( "\nGrade\tFrequency" );
for(int score: tests) {
System.out.println(score+"\t"+freq[score]);
}

```

As for the sort, you should be sorting the collection of scores, and to determine the sort order you can send an ascending flag to control order. E.g.

```System.out.println("Do you want to sort the scores in ascending or descending order? (a/d): ");
String ans = input.next();
if(ans.equalsIgnoreCase("a"))ascending = true;
else if(ans.equalsIgnoreCase("d"))ascending = false;

bubbleSort(tests, tests.length, ascending);

public static void bubbleSort( int[] freq, int length, boolean ascending );

if(ascending) {
if ( freq[ index ] > freq[ index + 1 ] ) {
swap();
}
}else {
if ( freq[ index ] < freq[ index + 1 ] ) {
swap();
}
}

```

This post has been edited by blackcompe: 22 September 2011 - 03:53 PM

### #5 cmpshr

Reputation: 42
• Posts: 120
• Joined: 22-August 11

## Re: difficulties in passing an array through a method for bubble sorting

Posted 22 September 2011 - 01:39 PM

creative code monkey, on 22 September 2011 - 12:18 PM, said:

You need to return the frequency array back to the calling program. An int[] isn't by reference, it's by value, so the bubbleSort() method makes it's own local copy of the array, and then just dumps it.

Sorry, array are Object and so passed by reference

```int[] x = {1, 2, 3, 4, 5}
foo(x);
...x[2] == 100

```

```void foo(int[] z) {
z[z.length / 2] = 100;
}

```

So the sort method can sort in the original

This post has been edited by cmpshr: 22 September 2011 - 01:40 PM

### #6 creative code monkey

Reputation: 14
• Posts: 45
• Joined: 14-September 11

## Re: difficulties in passing an array through a method for bubble sorting

Posted 22 September 2011 - 03:41 PM

Quote

Sorry, array are Object and so passed by reference
Yea, sorry about that, didn't realize primitive arrays were reference by reference. I don't use 'em much. I started playing around with it, and realized my mistake but didn't have time to correct it earlier.

Your bubble sort is working correctly as far as it's designed, just like blackcompe said.

This post has been edited by creative code monkey: 22 September 2011 - 03:42 PM

### #7 TheMantis

Reputation: 1
• Posts: 11
• Joined: 01-April 11

## Re: difficulties in passing an array through a method for bubble sorting

Posted 23 September 2011 - 11:11 AM

Thank you all for your help, however, after e-mailing my teacher about it she let me know that my code is basically correct, and that I don't actually have to sort it. I have to make two methods, one that outputs the frequencies in ascending order (like the first code that I posted) and then another method that does it in descending. From there, I will make a switch statement in the main method that calls upon the two methods depending on how the user would like the test scores displayed.
SO
I went ahead and decided to try and change the code so that it prints in descending order, before I do all that...and I was somewhat successful.

I changed my second for loop that dealt with printing the frequencies from this:
```for (int count = 0; count < freq.length; count++)
{
if (freq[count]>0)
{
System.out.println(count +"\t"+freq[count]);
}
}

```

to this:
```		for (int count = 100; count < freq.length; count--)
{
if (freq[count]>0)
{
System.out.println(count +"\t"+freq[count]);
}
}

```

And it does work...the program is now outputting the code in descending order HOWEVER after printing the last line I get the following exception:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
line 25 in this bit of code is the if statement:
```if (freq[count]>0)

```

and I don't see what the if statement has to do with the array index...
I tried messing around with the index in the for loop as well as with the length of the frequency array, but have had no success. It would seem that at the end of the loop the program tries to access an array element that is outside of the array's limits...but I don't know why. How can I fix this?

### #8 blackcompe

• D.I.C Lover

Reputation: 1159
• Posts: 2,547
• Joined: 05-May 05

## Re: difficulties in passing an array through a method for bubble sorting

Posted 23 September 2011 - 12:20 PM

```for (int count = 100; count < freq.length; count--)
```

The loop condition is wrong. If your starting at the end of the array and want to continue until the beginning it's .... hint ..... until 0.....flip your comparison operator.

Really, the for loop shouldn't even execute because count equals 100 and freq.length should equal 100 but it equals 101. Therefore, count is less than freq.length. You should really change the length of your arrays to be what they should be, which is the highest one can score on a test (100).

### #9 TheMantis

Reputation: 1
• Posts: 11
• Joined: 01-April 11

## Re: difficulties in passing an array through a method for bubble sorting

Posted 23 September 2011 - 12:54 PM

blackcompe, on 23 September 2011 - 12:20 PM, said:

```for (int count = 100; count < freq.length; count--)
```

The loop condition is wrong. If your starting at the end of the array and want to continue until the beginning it's .... hint ..... until 0.....flip your comparison operator.

Really, the for loop shouldn't even execute because count equals 100 and freq.length should equal 100 but it equals 101. Therefore, count is less than freq.length. You should really change the length of your arrays to be what they should be, which is the highest one can score on a test (100).

I've played around with making the frequency array length 100, but then it doesn't let me enter 100 as a grade (because then the array starts at 0 and goes to 99).

I also previously tried flipping the comparison operator, but this resulted in no output. The way I have it now gives me the output that I'm looking for, but it gives me the runtime error at the end. I don't know...maybe if I add some exception handling that will solve the problem? I will mess around with it more when I get home from work.

### #10 blackcompe

• D.I.C Lover

Reputation: 1159
• Posts: 2,547
• Joined: 05-May 05

## Re: difficulties in passing an array through a method for bubble sorting

Posted 23 September 2011 - 02:08 PM

Quote

I've played around with making the frequency array length 100, but then it doesn't let me enter 100 as a grade (because then the array starts at 0 and goes to 99).

I see. That's works, although you could just say:

```++freq[tests[index]-1];
```

Quote

I also previously tried flipping the comparison operator, but this resulted in no output. The way I have it now gives me the output that I'm looking for, but it gives me the runtime error at the end. I don't know...maybe if I add some exception handling that will solve the problem? I will mess around with it more when I get home from work.

Yes, but are you comparing the count to 0? E.g.

```for (int count = 100; count > 0; count--)
```