Bubble Sort In Java
Code :
public class BubbleSort {
static int swapCount=0;
static int passes=0;
public static void main(String[] args) {
int[] array={5,1,4,2,8};
printArray(array);//Before
bubbleSort(array);
printArray(array);//After
System.out.println("\n Total Passes:"+passes);
System.out.println("\n Total Swaps:"+swapCount);
}
private static void bubbleSort(int[] array) {
boolean swapped=false; //Needed to check if the pass swapped elements
do{ // needed as the loop should be entered atleast once
swapped=false; //keeping it false before entering the Pass
for(int i=0;i<array.length-1;i++){
if(array[i+1]<array[i]){ // If numbers are not in place swap
swap(i+1,i,array); // swap funtion
swapped=true; // elements swapped hence make it true
}
passes++; // just for reporting
}
}while(swapped);
System.out.println();
}
private static void swap(int a,int b,int[] arr){ // utility function to swap elements
int temp=arr[a];
arr[a]=arr[b];
arr[b]=temp;
System.out.println("\n Swapping a:"+arr[a]+" b:"+arr[b]);
swapCount++; // reporting the total swaps
}
private static void printArray(int[] arr){ //utility function to print array
for(int i=0;i<arr.length;i++){
System.out.print(" "+arr[i]);
}
System.out.println();
}
}
Comments
Post a Comment