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:
SyntaxError: invalid syntax python
How to Edit Shopify Themes Locally Using Git and Theme Kit
UnicodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte, python
How to use ASP.NET with Blazor
Project Java Build Form by multiple process
Using Dompdf: A Guide with Installation and Examples
DeprecationWarning: use of deprecated function or module, python
SystemError: unknown opcode, python