Bubble Sort Algorithm Using Java - Interview Tips

Bubble Sort Algorithm 

  • Bubble sort algorithm is known as the simplest sorting algorithm.
  • In Bubble sort algorithm, array is traversed from first element to last element. Here, current element is compared with the next element. If current element is greater than the next element, it is swapped.

Source Code:-

For Daily Java Tips Follow Click here👉👉👉  d_programming_ 👈👈👈Official Instagram
package main;

public class BubbleSort {
static void bubbleSort(int[] arr) {
int n = arr.length;
int temp = 0;
for(int i=0; i < n; i++){
for(int j=1; j < (n-i); j++){
if(arr[j-1] > arr[j]){
//swap elements
temp = arr[j-1];
arr[j-1] = arr[j];
arr[j] = temp;
}

}
}

}
public static void main(String[] args) {
int arr[] ={55,88,54,277,45,320,99,3,77,11};

System.out.println("Array Before Bubble Sort");
for(int i=0; i < arr.length; i++){
System.out.print(arr[i] + " ");
}
System.out.println();

bubbleSort(arr);//sorting array elements using bubble sort

System.out.println("Array After Bubble Sort");
for(int i=0; i < arr.length; i++){
System.out.print(arr[i] + " ");
}

}
}
Output: Array Before Bubble Sort
55 88 54 277 45 320 99 3 77 11 
Array After Bubble Sort
3 11 45 54 55 77 88 99 277 320 



CONVERSATION

0 Comments:

Post a Comment