Write a program that does bubble sort on an array?
Additional Info
Bubble sort is a simple sort, but not much used as there are many better sorting algorithms.
Question: Try to find out a situation where Bubble sort is advantageous.
Engineering Full Stack Apps with Java and JavaScript
Write a program that does bubble sort on an array?
Additional Info
Bubble sort is a simple sort, but not much used as there are many better sorting algorithms.
Question: Try to find out a situation where Bubble sort is advantageous.
package com.javajee.myBubbleSort;
public class BubbleSort {
int[] arrayElements= {9,4,10,6,8};
public static void main(String[] args) {
BubbleSort BS= new BubbleSort();
BS.arrangeElements(BS.arrayElements,BS.arrayElements.length);
}
//method to sort elements
public void arrangeElements(int[]array,int length){
int i=0;
int j=0;
int temp=0;
for(i=0;i<length;i++){
for(j=1;j<length-i;j++){
if(array[j-1]>array[j]){
temp=array[j-1];
array[j-1]=array[j];
array[j]=temp;
}
}
}
//printing sorted array
for(int e:array){
System.out.println(e);
}
}
}
In bubble sort, we start with comparing first two elements and elements are swapped if first element is larger than second element. This process continues till the end of the array so that the largest element becomes the last element. Again the process starts from the beginning till the second last element. Process continues untill all the elements are sorted