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:
Get LinkedIn skill assessments with Quiz Solver plugin
ZeroDivisionError: division by zero, python
UnicodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte, python
Creating a Binary Search Tree in Java
SyntaxError: invalid syntax python
RecursionError: maximum recursion depth exceeded, python
NameError: name 'x' is not defined python
AssertionError: assert condition, error_message, python