BUBBLE SORT PROGRAM
Bubble Sort is a simple sorting algorithm that repeatedly steps through the list, compares adjacent elements and swaps them if they are in the wrong order. The pass through the list is repeated until the list is sorted.
Here is a simple implementation of Bubble Sort in Java:
public class BubbleSort {
void bubbleSort(int arr[]) {
int n = arr.length;
for (int i = 0; i < n-1; i++)
for (int j = 0; j < n-i-1; j++)
if (arr[j] > arr[j+1]) {
// swap arr[j+1] and arr[j]
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
/* Prints the array */
void printArray(int arr[]) {
int n = arr.length;
for (int i=0; i<n; ++i)
System.out.print(arr[i] + " ");
System.out.println();
}
// Driver method to test above
public static void main(String args[]) {
BubbleSort bs = new BubbleSort();
int arr[] = {64, 34, 25, 12, 22, 11, 90};
bs.bubbleSort(arr);
System.out.println("Sorted array");
bs.printArray(arr);
}
}
In this code, bubbleSort(int arr[])
is the method that implements the Bubble Sort algorithm. It takes an array of integers as input and sorts the array in ascending order. The printArray(int arr[])
method is used to print the elements of the array. The main(String args[])
method is the entry point of the program. It creates an instance of the BubbleSort
class, defines an array of integers, sorts it using the bubbleSort
method, and then prints the sorted array.