Bubble Sort Program in java
Code::
import java.util.*;
import java.lang.*;
import java.io.*;
//Bubble Sort
class Test{
public static void main(String[] args){
int[] arr = {2,7,4,1,5,3};
bubble(arr);
for(int i : arr){
System.out.print(i+" ");
}
}
public static void bubble(int[] arr){
for(int i=0;i<arr.length;i++){
//the last val is at its correct Position
for(int j=0;j<arr.length-i-1;j++){
if(arr[j]>arr[j+1]){
//swap
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
}
Optimized code if the right part of the array is sorted
code:
import java.util.*;
import java.lang.*;
import java.io.*;
//Bubble Sort
class Test{
public static void main(String[] args){
int[] arr = {2,7,4,1,5,3};
bubble(arr);
for(int i : arr){
System.out.print(i+" ");
}
}
public static void bubble(int[] arr){
for(int i=0;i<arr.length;i++){
int swap = 0;
for(int j=0;j<arr.length-i-1;j++){
if(arr[j]>arr[j+1]){
swap = 1;
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
if(swap==0){
break;
}
}
}
}
Comments
Post a Comment