📘 Lesson · Lesson 51
Bubble Sort
Bubble Sort
Bubble Sort Program in Java
Bubble sort repeatedly swaps adjacent elements that are out of order, so the largest "bubbles" to the end each pass.
Java Program
int[] a = {5, 2, 8, 1, 9};
int n = a.length;
for (int i = 0; i < n - 1; i++)
for (int j = 0; j < n - i - 1; j++)
if (a[j] > a[j + 1]) {
int t = a[j]; a[j] = a[j + 1]; a[j + 1] = t;
}
System.out.println(java.util.Arrays.toString(a));
Output
[1, 2, 5, 8, 9]
How it Works
- Two nested loops compare neighbours and swap if out of order.
- After each outer pass, the next largest value is in place.
Summary
- Bubble sort repeatedly swaps adjacent elements that are out of order, so the largest "bubbles" to the end each pass.
Bubble Sort Program in Java
Bubble sort बार-बार adjacent elements swap करता है जो गलत क्रम में हों, ताकि सबसे बड़ा हर pass में अंत तक "bubble" हो।
Java Program
int[] a = {5, 2, 8, 1, 9};
int n = a.length;
for (int i = 0; i < n - 1; i++)
for (int j = 0; j < n - i - 1; j++)
if (a[j] > a[j + 1]) {
int t = a[j]; a[j] = a[j + 1]; a[j + 1] = t;
}
System.out.println(java.util.Arrays.toString(a));
Output
[1, 2, 5, 8, 9]
कैसे काम करता है
- दो nested loops neighbours compare करके गलत क्रम पर swap करते हैं।
- हर outer pass के बाद अगली सबसे बड़ी value अपनी जगह पर आ जाती है।
सारांश
- Bubble sort बार-बार adjacent elements swap करता है जो गलत क्रम में हों, ताकि सबसे बड़ा हर pass में अंत तक "bubble" हो।