-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathAlmostSorted.java
99 lines (83 loc) · 3.04 KB
/
AlmostSorted.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
// https://www.hackerrank.com/challenges/almost-sorted/problem
package implimentation;
import java.util.Arrays;
import java.util.Scanner;
public class AlmostSorted {
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
int length = scanner.nextInt();
int[] array = getArray(length);
operationForSort(array);
}
private static void operationForSort(int[] array) {
if (isSorted(array)) {
System.out.println("yes");
return;
}
int[] sortedArray = sortedArray(array);
int leftMisplacedIndex = leftMisplacedIndex(array, sortedArray);
int rightMisplacesIndex = rightMisplacedIndex(array, sortedArray);
swap(array, leftMisplacedIndex, rightMisplacesIndex);
if (isSorted(array)) {
System.out.println("yes");
System.out.println(String.format("swap %d %d", leftMisplacedIndex + 1, rightMisplacesIndex + 1));
return;
}
swap(array, leftMisplacedIndex, rightMisplacesIndex);
int[] reversed = reverse(array, leftMisplacedIndex, rightMisplacesIndex + 1);
if (isSorted(reversed)) {
System.out.println("yes");
System.out.println(String.format("reverse %d %d", leftMisplacedIndex + 1, rightMisplacesIndex + 1));
return;
}
System.out.println("no");
}
private static int[] sortedArray(int[] array) {
int[] sortedArray = array.clone();
Arrays.sort(sortedArray);
return sortedArray;
}
private static int[] reverse(int[] array, int startIndex, int endIndex) {
int[] reversed = new int[endIndex - startIndex];
for (int index = startIndex ; index < endIndex ; index++) {
reversed[index - startIndex] = array[endIndex - index + startIndex - 1];
}
return reversed;
}
private static void swap(int[] array, int a, int b) {
int temp = array[a];
array[a] = array[b];
array[b] = temp;
}
private static int leftMisplacedIndex(int[] array, int[] sortedArray) {
for (int index = 0 ; index < array.length ; index++) {
if (array[index] != sortedArray[index]) {
return index;
}
}
return -1;
}
private static int rightMisplacedIndex(int[] array, int[] sortedArray) {
for (int index = array.length - 1 ; index >= 0 ; index--) {
if (array[index] != sortedArray[index]) {
return index;
}
}
return -1;
}
private static boolean isSorted(int[] array) {
for (int index = 0 ; index < array.length - 1 ; index++) {
if (array[index] > array[index + 1]) {
return false;
}
}
return true;
}
private static int[] getArray(int length) {
int[] array = new int[length];
for (int index = 0 ; index < array.length ; index++) {
array[index] = scanner.nextInt();
}
return array;
}
}