The worst case scenario in the time it takes to sort data with bubble sort is O(n²). It’s not best to use this type of sorting algorithm when you have a lot of data, but it’s efficient when you have a small amount of data. Whenever I make a game that has high scores, I use this algorithm, because it only sorts 10 numbers.
This can help illustrate how bubble sorting works when wanting larger numbers first:
- The first two numbers are compared.
- If the second is higher than the first, these numbers are swapped. If not, nothing happens.
- The second and third numbers are compared. If the third is higher than the second, these numbers are swapped. If not, nothing happens.
- Repeat all the way to the last two numbers. This guarantees the lowest number is at the end of the list.
- Repeat all of this over again, but for all numbers except the last because the last is guaranteed to be the smallest number.
- Repeat if again for all numbers except the last two because the last two are guaranteed to be sorted.
- Each time you do this and go through the set, one more number is sorted. Once you are at the first and second number and you do the check and swap if needed, the entire list will be sorted.
I made the following tutorial years ago:
public class BubbleSort
{
private static int list1[] = new int[]{5, 2, 3, 9, 4, 7, 12, 1, 0, 6};
private static int list2[] = new int[]{2, 7, 8, 1, 4, 0, -2, 4, 8, 10};
public static void main(final String[] args)
{
sortAscending(list1);
sortDescending(list2);
System.out.print("Ascending: ");
for (int i : list1)
{
System.out.print(i + " ");
}
System.out.print("\nDescending: ");
for (int i : list2)
{
System.out.print(i + " ");
}
}
private static void sortAscending(final int[] array)
{
int temp;
for (int c = 0; c < array.length - 1; c++)
{
for (int d = 0; d < array.length - c - 1; d++)
{
if (array[d] > array[d + 1])
{
temp = array[d];
array[d] = array[d + 1];
array[d + 1] = temp;
}
}
}
}
private static void sortDescending(final int[] array)
{
int temp;
for (int c = 0; c < array.length - 1; c++)
{
for (int d = 0; d < array.length - c - 1; d++)
{
if (array[d] < array[d + 1])
{
temp = array[d];
array[d] = array[d + 1];
array[d + 1] = temp;
}
}
}
}
}
You can download other Java code I’ve made here:
One response to “Bubble Sort Algorithm in Java”
[…] Bubble Sort Algorithm (explanation and Java source code) […]
LikeLike