Sorting: Bubble Sort
Solution :-
import java.util.*;
class sort{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int ar[]=new int[n];
for(int i=0;i<n;i++){
ar[i]=sc.nextInt();
}
int swap=0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n - 1; j++) {
if (ar[j] > ar[j + 1]) {
int temp=ar[j];
ar[j]=ar[j+1];
ar[j+1]=temp;
swap++;
}
}
}
System.out.println("Array is sorted in "+swap +" swaps.");
System.out.println("First Element: "+ar[0]);
System.out.println("Last Element: "+ar[n-1]);
}
}
0 Comments