Sorting in JAVA
Bubble Sort
Idea: if arr[i] > arr[i+1] swap them. To place the element in their respective position, we have to do the following operation N-1 times.
Time Complexity: O(N2)
Code
import java.util.*;
s
class Sorting {
public static void printArray(int arr[]) {
for(int i=0; i<arr.length; i++) {
System.out.print(arr[i]+" ");
}
System.out.println();
}
public static void main(String args[]) {
int arr[] = {7, 8, 1, 3, 2};
//bubble sort
for(int i=0; i<arr.length-1; i++) {
for(int j=0; j<arr.length-i-1; j++) {
if(arr[j] > arr[j+1]) {
//swap
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
printArray(arr);
}
}
Sure! Here's an implementation of the Bubble Sort algorithm in Java:
csspublic 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;
} } } }
In this implementation, arr is the unsorted array, n is the length of the array, and i and j are loop variables. The inner loop (for j) compares adjacent elements and swaps them if necessary. The outer loop (for i) controls how many times the inner loop should be executed.
To use this method, you can simply call it with your array as an argument:
int[] arr = {5, 2, 8, 3, 1, 6}; bubbleSort(arr);
After the method returns, arr will be sorted in ascending order.
Note that, like the Python implementation, this implementation of Bubble Sort has a time complexity of O(n^2), which means that it can be slow for large arrays.
Comments
Post a Comment