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:
Debugging Javascript Code
How to use ASP.NET with Blazor
DeprecationWarning: use of deprecated function or module, python
IndentationError: unexpected indent, python
OSError: [Errno 2] No such file or directory: 'file_name', in python
StopIteration: iteration ended before completion, python
Building a Priority Queue in Java
SystemError: unknown opcode, python