Bubble sort is a simple sorting algorithm that repeatedly compares adjacent elements and swaps them if they are in the wrong order. The algorithm gets its name from the way smaller elements "bubble" to the top of the list. Bubble sort is not efficient for large datasets but can be useful for small datasets or as an educational tool to understand sorting algorithms.
The purpose of using bubble sort is to sort a given array or list in ascending or descending order. It is straightforward to implement and does not require any additional data structures. However, due to its simplicity, bubble sort has a time complexity of O(n^2), making it inefficient for large datasets. There are more efficient sorting algorithms available, such as merge sort or quicksort, that are generally preferred for practical use.
Here's an example of how you can implement bubble sort in Java:
public class BubbleSortExample {
public static void main(String[] args) {
int[] arr = {5, 2, 8, 12, 3};
System.out.println("Original array: ");
printArray(arr);
bubbleSort(arr);
System.out.println("Sorted array: ");
printArray(arr);
}
public static 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] and arr[j + 1]
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
public static void printArray(int[] arr) {
for (int element : arr) {
System.out.print(element + " ");
}
System.out.println();
}
}
No comments:
Post a Comment