I have a piece of code which fills an ArrayList<Integer>
with random integers from 10 to 99 (two digit numbers). It is then supposed to iterate through the array and sort it using bubble sort (or exchange sort, to be honest, I'm not quite sure what the difference is). However, the output that I get is really weird. Attached is the code and example output from it.
import java.util.*;
public class SortingAnArrayList
{
public static void main( String[] args )
{
ArrayList<Integer> al = new ArrayList<>();
Random r = new Random();
for ( int i = 0; i < 20; i++ )
{
int rNum = 10 + r.nextInt(90);
al.add( rNum );
}
System.out.println( "ArrayList before: " + al);
ArrayList<Integer> sortedAl = sortArrayList(al);
System.out.println( "ArrayList after : " + sortedAl);
}
public static ArrayList<Integer> sortArrayList( ArrayList<Integer> a )
{
boolean loop;
ArrayList<Integer> b = a;
do
{
loop = false;
for ( int i = 0; i < a.size() - 2; i++ )
{
if ( b.get(i) > b.get(i + 1) )
{
loop = true;
int temp = b.get(i);
b.remove(i);
b.add( i, b.get(i+1) );
b.remove(i+1);
b.add( i+1, temp );
}
}
} while (loop);
return b;
}
}
OUTPUT #1
ArrayList before: [45, 33, 75, 51, 91, 93, 54, 91, 90, 38, 31, 85, 15, 33, 61, 51, 83, 36, 48, 18]
ArrayList after : [93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 18]
OUTPUT 2
ArrayList before: [73, 39, 68, 54, 12, 63, 90, 55, 53, 24, 14, 80, 58, 12, 64, 25, 82, 27, 20, 55]
ArrayList after : [12, 12, 20, 55, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 55]
Please help as I'm not quite sure where I went wrong with the code. Thanks!