Bubble sort algorithm is the simplest sorting algorithm. In bubble sort algorithm, array is traversed from first element to last element. Here, first element is compared with the next element. If first element is greater than the next element,then it is swapped.
import java.util.Arrays;
public class BubbleSort {
public static void method_1(int[] arr){
System.out.println("ELEMENTS BEFORE SORTING : ");
for (int i : arr) {
System.out.print(i+",");
}
for(int i=0 ; i < arr.length ; i++){
for(int j=0 ; j < arr.length-1 ;j++){
if(arr[j] > arr[j+1]){
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
System.out.println("\n\nELEMENTS AFTER SORTING : ");
for (int i : arr) {
System.out.print(i+",");
}
}
public static void method_2(int[] arr){
System.out.println("\n\nSORTING USING PREDEFINED METHOD : ");
Arrays.sort(arr);
for(int i : arr){
System.out.print(i+",");
}
}
public static void main(String[] args) {
int[] arr = {5,6,3,1,2};
BubbleSort.method_1(arr);
BubbleSort.method_2(arr);
}
}
Program Output :-
ELEMENTS BEFORE SORTING :
5,6,3,1,2,
ELEMENTS AFTER SORTING :
1,2,3,5,6,
SORTING USING PREDEFINED METHOD :
1,2,3,5,6,
No comments:
Post a Comment