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
MemoryError: out of memory, python
How to use ASP.NET with Blazor
Get LinkedIn skill assessments with Quiz Solver plugin
KeyboardInterrupt: user interrupts the program by pressing Ctrl+C, python
Warning: non-fatal alert, usually indicating potential issues with code, python
SystemError: unknown opcode, python
DeprecationWarning: use of deprecated function or module, python