-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.java
More file actions
34 lines (29 loc) · 998 Bytes
/
Solution.java
File metadata and controls
34 lines (29 loc) · 998 Bytes
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
32
33
34
import java.util.Scanner;
public class Solution {
private static final Scanner scan = new Scanner(System.in);
private static int bubbleSort(int[] arr) {
int numSwaps = 0;
for (int i = 0; i < arr.length - 1; i++) {
for (int j = 0; j < arr.length - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
numSwaps++;
}
}
if (numSwaps == 0) break;
}
return numSwaps;
}
public static void main(String[] args) {
int n = scan.nextInt();
int[] arr = new int[n];
for (int i = 0; i < arr.length; i++) {
arr[i] = scan.nextInt();
}
System.out.printf("Array is sorted in %d swaps.%nFirst Element: %d%nLast Element: %d",
bubbleSort(arr), arr[0], arr[arr.length - 1]);
scan.close();
}
}