Bubble Sort is a simple sorting algorithm that repeatedly steps through a list, comparing adjacent elements and swapping them if they are in the wrong order.
Reason
Bubble Sort is a simple and easy to understand algorithm and is often the first sorting algorithm that students learn. Despite its simplicity, it is not the most efficient sorting algorithm and is used mostly in educational contexts.
Example Code with Output
public class BubbleSort {
public static void main(String[] args) {
int[] intArray = { 20, 35, -15, 7, 55, 1, -22 };
for (
int lastUnsortedIndex = intArray.length - 1;
lastUnsortedIndex > 0;
lastUnsortedIndex--
) {
for (int i = 0; i < lastUnsortedIndex; i++) {
if (intArray[i] > intArray[i + 1]) {
swap(intArray, i, i + 1);
}
}
}
for (int i = 0; i < intArray.length; i++) {
System.out.println(intArray[i]);
}
}
public static void swap(int[] array, int i, int j) {
if (i == j) {
return;
}
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
Output:
-22
-15
1
7
20
35
55
Related Quiz:
IndentationError: unexpected indent, python
OSError: [Errno 2] No such file or directory: 'file_name', in python
Debugging Javascript Code
UnicodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte, python
How to Edit Shopify Themes Locally Using Git and Theme Kit
Building a Priority Queue in Java
Get LinkedIn skill assessments with Quiz Solver plugin
ValueError: invalid literal for int() with base 10 , python