-
Notifications
You must be signed in to change notification settings - Fork 178
/
Copy pathday 20.java
31 lines (31 loc) · 1000 Bytes
/
day 20.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import java.util.*;
public class Solution {
//bubble sort is mentioned in question..
//else the best sorting algorithm would be quick sort...
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n = sc.nextInt();
int[] a=new int[n];
for(int i=0;i<n;i++)
a[i]=sc.nextInt();
int numberOfSwaps=0;
for (int i=0;i<n;i++)
{
for (int j=0;j<n-1;j++)
{
if (a[j]>a[j+1])
{
//below three lines are used for swapping...
int temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
numberOfSwaps++;
}
}
if (numberOfSwaps==0) break;
}
System.out.println("Array is sorted in "+numberOfSwaps+" swaps.");
System.out.println("First Element: "+a[0]);
System.out.println("Last Element: "+a[n-1]);
}
}