-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDay20.java
More file actions
47 lines (38 loc) · 1.29 KB
/
Day20.java
File metadata and controls
47 lines (38 loc) · 1.29 KB
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
35
36
37
38
39
40
41
42
43
44
45
46
47
import java.util.Scanner;
public class Solution {
private static int[] array;
private static void bubbleSort() {
int n = array.length;
// number of swaps for all array iterations
int totalSwaps = 0;
for (int i = 0; i < n; i++) {
// number of swaps for current array iteration
int numSwaps = 0;
for (int j = 0; j < array.length - 1; j++) {
if (array[j] > array[j + 1]) {
int tmp = array[j];
array[j] = array[j + 1];
array[j + 1] = tmp;
numSwaps++;
totalSwaps++;
}
}
if (numSwaps == 0) {
System.out.printf("Array is sorted in %d swaps.\n", totalSwaps);
System.out.printf("First Element: %d\n", array[0]);
System.out.printf("Last Element: %d\n", array[n - 1]);
break;
}
}
}
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int n = in.nextInt();
array = new int[n];
for (int i = 0; i < n; i++) {
array[i] = in.nextInt();
}
in.close();
bubbleSort();
}
}