I tried to make an implementation of bubble sort, but I am not sure whether it is correct or not. If you can give it a look and if it is a bubble sort and can be done in better way please don't be shy. Here is the code:
package Exercises;
import java.util.*;
public class BubbleSort_6_18
{
public static void main(String[] args)
{
Random generator = new Random();
int[] list = new int[11];
for(int i=0; i<list.length; i++)
{
list[i] = generator.nextInt(10);
}
System.out.println("Original Random array: ");
printArray(list);
bubbleSort(list);
System.out.println("\nAfter bubble sort: ");
printArray(list);
}
public static void bubbleSort(int[] list)
{
for(int i=0; i<list.length; i++)
{
for(int j=i + 1; j<list.length; j++)
{
if(list[i] > list[j])
{
int temp = list[i];
list[i] = list[j];
list[j] = temp;
}
}
}
}
public static void printArray(int[] list)
{
for(int i=0; i<list.length; i++)
{
System.out.print(list[i] + ", ");
}
}
}
I think you got the idea of bubble sort by looking at your code:
Bubble sort usually works like the following: Assume aNumber is some random number:
How bubble sort is it iterates through every single possible spot of the array. i x j times The down side to this is, it will take square the number of times to sort something. Not very efficient, but it does get the work done in the most easiest way.
}