Posts

Showing posts from November, 2021

Bubble Sort Program in Java

Image
                      BUBBLE SORT PROGRAM USING JAVA                                           In Bubble sort we compare two consecutive elements of an array, if first one element is greater than next one then swap them. The time complexity in worst and average case is O(n^2) while in best case is O(n) and the space complexity is O(1) . package bubbleSort; public class BubbleSort { public static void bubbleSort(int[] arr) { for(int i=0; i<arr.length; i++) { for(int j=i+1; j<arr.length; j++) { if(arr[i] > arr[j]) { // swap the numbers int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } } }          // main method  public static void main(String[] args) {         // declare and assign an unsorted array  int[] array = {5, 1, 6, 2, 4, 3, 0, 5, 9}; // call the bubble sort function bubbleSort(array); // print the sorted array for(int e: array) { System.out.print(e + " "); } } } outp