Bubble Sort
In this post we are discuss about details Bubble Sort, Actually Bubble Sort is a simple sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. It is called "Bubble Sort" because smaller elements "bubble" to the top of the list (or larger elements sink to the bottom) with each iteration.
How It Works
- Outer Loop: Controls the number of passes. In each pass, the largest (or smallest) element moves to its correct position.
- Inner Loop: Compares adjacent elements and swaps them if needed.
- Optimization: If no swaps are made during a pass, the array is already sorted, and the algorithm can terminate early.
Program :
import java.util.*;
import java.util.Random;
class Bubble_Sort{
static int[] sort(int[] sequence ){
// Bubble_Sort Proccesure Start
for (int i = 0; i<sequence.length; i++){
for (int j = 0; j<sequence.length-1; j++){
if(sequence [j] > sequence[j+1]){
sequence[j]= sequence[j]+sequence[j+1];
sequence[j+1] = sequence [j] -sequence[j+1];
sequence[j] = sequence[j] -sequence[j+1];
}
}
}
return sequence;
}
static void printSequn(int[] sorted_sequence){
for (int i= 0; i<sorted_sequence.length;i++){
System.out.println(sorted_sequence[i] + " ");
}
}
// Random Number Generated Program from Here :-
public static void main(String args[]){
System.out.println("Sorting of randomly generatd numbers using BUBBLE SORT");
Random random = new Random();
int N = 10;
int[] sequence = new int[N];
for(int i=0; i< N; i++ ){
sequence[i]= Math.abs(random.nextInt(1000));
}
System.out.println("\n Orginal Sequence:");
printSequn(sequence);
System.out.println("\n Sorted Sequence: ");
printSequn(sort(sequence));
}
}
Explanation:
This program demonstrates the Bubble Sort algorithm by sorting a sequence of randomly generated numbers.
Output Example:
PS D:\Learning File\BCA\BCA 3rd Sem\JAVA OOP\Allpraque> javac 10q_BubbleSort.java
PS D:\Learning File\BCA\BCA 3rd Sem\JAVA OOP\Allpraque> java Bubble_Sort
Sorting of randomly generatd numbers using BUBBLE SORT
Orginal Sequence:
364
517
811
577
295
284
885
440
768
208
Sorted Sequence:
208
284
295
364
440
517
577
768
811
885
Comments