-
Notifications
You must be signed in to change notification settings - Fork 0
/
Day_20_Solution.java
54 lines (46 loc) · 1.45 KB
/
Day_20_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
42
43
44
45
46
47
48
49
50
51
52
53
54
/**
* Title : Day_20_Solution.java
* Author : Tridib Samanta
* Created : 15-01-2020
* Link : https://www.hackerrank.com/challenges/30-sorting/problem
**/
import java.util.Scanner;
public class Day_20_Solution {
private static int swaps = 0;
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int size = scan.nextInt();
int [] array = new int[size];
for (int i = 0; i < size; i++) {
array[i] = scan.nextInt();
}
scan.close();
bubbleSort(array);
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 bubbleSort(int [] array) {
if (array == null) {
return;
}
boolean swapped = true;
int endOffset = 0;
while (swapped) {
swapped = false;
for (int i = 1; i < array.length - endOffset; i++) {
if (array[i-1] > array[i]){
swap(array, i-1, i);
swapped = true;
}
}
endOffset++;
}
}
private static void swap(int [] array, int i, int j) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
swaps++;
}
}