In this tutorial, We can create a bubble sort program in java to sort array elements. Bubble Sort Algorithm is called the simplest sorting algorithm. This Bubble Sort in Java tutorial will, therefore, allow you to understand the concept in depth.
We’ll be covering the following topics in this tutorial:
What is Bubble Sort in Java
This sorting algorithm is a comparison algorithm that compares any pair of adjacent elements and swaps them in sequence. This sorting method proceeds until the last two array items compare and exchanged if not in sequence.
Time Complexity of Bubble Sort in Java
This algorithm is not ideal for big datasets as the mean complexity of this algorithm is O(n2). It implies that the time taken to sort such an array increases quadratically as the size array increases—that why programmers choose other sorting algorithms.
Bubble Sort Algorithm in Java
step 1: read num step 2: create an integer array a[] of size num step 3: set flag = 1 step 4: initialize i = 0 step 5: repeat through step-11 while (i<;n) and flag = l step 6: Reset flag = 0 step 7: Initialize j = 0 step 8: repeat through step-10 while (j<n-i-1) step 9: compare a[j] and a [j+ 1] if (a[j] > a[j+ 1]) then set the flag= 1 and interchange a[j] and a [j + 1] step 10: increment the value of 'j' as j = j + 1 step 11: increment the value of 'i' as i = i + 1 step 12: Exit
Bubble Sort Program in Java
import java.util.Scanner; public class BubbleSort { public static void main(String args[]) { int i,j,t,d; Scanner s=new Scanner(System.in); System.out.println("Enter The size of Array"); d=s.nextInt(); int a[]=new int[15]; System.out.println("\nEnter the Elements Are"); for(i=1;i<=d;i++) { a[i]=s.nextInt(); } System.out.print("\nElements Are\n"); for(i = 1;i <= d; i++) { System.out.print(a[i]+"\t"); } for(i = 1;i <= d;i++) { for(j = 1;j<(d-1); j++) { if(a[j] < a[j+1]) { t = a[j]; a[j] = a[j+1]; a [j+1] = t ; } } } System.out.println("\nAfter Bubble Sort is : \n"); for(i=1;i<=d;i++) { System.out.print(a[i ]+"\t") ; } } }