forked from sknsht/HackerRank
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Solution.java
41 lines (35 loc) · 1.08 KB
/
Solution.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
32
33
34
35
36
37
38
39
40
41
import java.util.*;
public class Solution {
private static void bubbleSort(int[] array) {
int swaps = 0;
boolean swapped = true;
while (swapped) {
swapped = false;
for (int i = 1; i < array.length; i++) {
if (array[i - 1] > array[i]) {
swap(array, i - 1, i);
swaps++;
swapped = true;
}
}
}
System.out.println("Array is sorted in " + swaps + " swaps.");
System.out.println("First Element: " + array[0]);
System.out.println("Last Element: " + array[array.length - 1]);
}
private static void swap(int[] array, int i, int j) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] array = new int[n];
for (int i = 0; i < n; i++) {
array[i] = in.nextInt();
}
in.close();
bubbleSort(array);
}
}