bubble sort in java
javaBubble sort is a simple sorting algorithm that repeatedly compares adjacent elements in an array and swaps them if they are in the wrong order. It continues this process until the array is sorted in ascending or descending order.
Here is an example of how to implement bubble sort in Java:
public class Main {
public static void main(String[] args) {
// Create an array of integers
int[] numbers = { 5, 2, 7, 1, 4 };
// Sort the array using bubble sort
bubbleSort(numbers);
// Print the sorted array
for (int number : numbers) {
System.out.print(number + " ");
}
// prints "1 2 4 5 7 "
}
// Bubble sort method
public static void bubbleSort(int[] numbers) {
// Flag to indicate if a swap was made in the current pass
boolean swapped;
do {
// Set the flag to false
swapped = false;
// Loop through the array
for (int i = 0; i < numbers.length - 1; i++) {
// If the current element is greater than the next element, swap them
if (numbers[i] > numbers[i + 1]) {
int temp = numbers[i];
numbers[i] = numbers[i + 1];
numbers[i + 1] = temp;
// Set the flag to true
swapped = true;
}
}
} while (swapped); // Repeat the process until no swaps are made
}
}
This code defines a bubbleSort()
method that uses a do
-while
loop to repeatedly compare and swap adjacent elements
in
the array until it is sorted. It then prints the sorted array to the console.
Keep in mind that bubble sort is not a very efficient sorting algorithm, especially for large arrays, and there are faster sorting algorithms available such as quicksort and mergesort.
Other Article on Tag java
- - after and before in java date
- - am pm java date format
- - apk minecraft java edition
- - as been blocked by CORS policy Response to preflight request doesn't pass access control check It does not have HTTP ok status
- - bubble sort in java
- - Can I compile and run a spring boot jar from inside another spring boot application
- - convert java date to localdate
- - design patterns in java
- - encrypt by java and decrypt by node
- - exception handling in java