You are on page 1of 4

Bubble Sort Program:/*

* This program uses the sophisticated bubble sort to sort the array of integers.
* @author Sreesowmya Chaturvedula
*/
package spsu;
import java.util.Scanner;
import java.util.Random;
public class BubbleSort {
public static void main(String[]args){
Scanner scan=new Scanner(System.in);
//Taking user inputs for number of elements to be present in an array
System.out.println("Please enter the number of elements to be there in array:");
int numberOfElements=scan.nextInt();
int[]arrayName=new int[numberOfElements];
int i=0;
//create an object random of class Random to generate random integers.
Random random=new Random();
//create a for loop to access the individual elements of array
for(i=0;i<arrayName.length;i++){
arrayName[i]=random.nextInt();
}
//Display the array before bubble sort
System.out.println("Before Bubble sort the array is:");
for(i=0;i<arrayName.length;i++)
System.out.print(arrayName[i]+"\t");
System.out.println();
//call the bubbleSort method to sort the given array
bubbleSort(arrayName);
//Display the array after being sorted using bubbleSort
System.out.println("After Bubble sort the array is:");
for(i=0;i<arrayName.length;i++)
System.out.print(arrayName[i]+"\t");
System.out.println();
}
/**
* create bubbleSort method to sort an array
* @param array is the list of randomly generated integers
*/
public static void bubbleSort(int[] array){
int n=array.length;
int lastSwap=1;
for(int i=n;i>0;i--){
for(int j=1;j<i;j++){
if(array[j-1]>array[j]){
int temp = array[j-1];
array[j-1] = array[j];
array[j]=temp;
lastSwap=j;
}
}
n=lastSwap;
}
}
}

Program Run 1:-

Program Run2:-

Program Run 3:-

You might also like