# Bubble sort

• 04-24-2009, 05:18 PM
pineapple
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[100];

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);
}
• 04-24-2009, 11:12 PM
markw8500
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...

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:

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

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:

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:

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...
• 04-25-2009, 12:55 AM
CJSLMAN
Arrays are 0 indexed
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 [0] not [1]. Therefore, your "for" loop should look like:
Code:

`for (int i = [B][COLOR="Blue"]0[/COLOR][/B]; i [B][COLOR="blue"]<[/COLOR][/B] 100; ++i)`
Luck,
CJSL
• 04-25-2009, 01:45 AM
markw8500
Good catch... I didn't even see that...