In Bubble Sort, we always compare one array element with its adjacent element. If the first element is greater than the next element, we swap both of them. These steps will be repeated several times to push all the big numbers to the end one after one.
Program:
package com.techstackjournal;
public class BubbleSort {
public static void main(String[] args) {
int arr[] = { 22, 15, 29, 11, 4 };
int index = arr.length - 2;
for (int i = 0; i <= index; i++) {
for (int j = 0; j <= index - i; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
for (int i : arr) {
System.out.println(i);
}
}
}
Output:
4
11
15
22
29
Leave a Reply