1. Member Join Date
Apr 2009
Posts
1
Rep Power
0

## Bubble sort

i have this code and i need to bubble sort the randomly generated numbers. I have tried writing code to do it but i am completely stumped. How can this code be bubble sorted

import java.util.Random;
import java.io.*;
import java.*;

public class RandomIntegerMFecteau {

public static final void main(String... aArgs){
System.out.println("Generate 100 random numbers.");

int[] ArrayOne = new int;

Random randomGenerator = new Random();
for (int i = 1; i <= 100; ++i){
ArrayOne[i] = randomGenerator.nextInt(1000);
log("Generated : " + ArrayOne[i]);
}

System.out.println("Done.");
}

private static void log(String aMessage){
System.out.println(aMessage);
}  Reply With Quote

2. ## Bubble Sorting is kinda neet but I never had a practical use for it... Check out:Bubble sort - Wikipedia, the free encyclopedia... They have a pretty cool diagram and explanation on how it works...

But basically you will need 3 methods...
-insert
-swap
-sort

So if I were you I would create a new class and call it BubbleSort...

In the constructor you will set the maxvalue of the array and initalize your element int...

Java Code:
```        public BubbleSort(int maxLength) {
a = new long[maxLength];
element= 0;

}```

Your insert method, will be used to insert a value into your array... Like so:

Java Code:
```        public void insert(long value) {
a[element] = value;
element++;
}```

Your swap method will be used to swap the places of the two elements if the value on the right is greater than the value on the left...

Java Code:
```     private void swap(int one, int two) {
long temp = a[one];
a[one] = a[two];
a[two] = temp;
}```
Now the final method is where all the action occurs... The actual sorting:

Java Code:
```
public void sort() {
int out,  in;
for (out = element- 1; out > 1; out--) {
for (in = 0; in < out; in++) {
if (a[in] > a[in + 1]) {
swap(in, in + 1);
}
}
}
}```

Now all you will have to do is in your for do something like:

Java Code:
```     for (int i = 1; i <= 100; ++i){
myBubbleSortObject.insert(randomGenerator.nextInt(1000));
log("Generated : " + ArrayOne[i]);
}

myBubbleSortObject.sort();```
And after a while... Your array will be sorted...
Last edited by markw8500; 04-24-2009 at 11:14 PM.  Reply With Quote

3. ## Arrays are 0 indexed

Java Code:
`for (int i = [COLOR="Red"][B]1[/B][/COLOR]; i [COLOR="red"][B]<=[/B][/COLOR] 100; ++i)`
Arrays are 0 indexed, which means that the first element of the the array is  not . Therefore, your "for" loop should look like:
Java Code:
`for (int i = [B][COLOR="Blue"]0[/COLOR][/B]; i [B][COLOR="blue"]<[/COLOR][/B] 100; ++i)`
Luck,
CJSL  Reply With Quote

4. ## Good catch... I didn't even see that...  Reply With Quote

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•