-
Notifications
You must be signed in to change notification settings - Fork 0
/
SwapProblem.java
53 lines (50 loc) · 915 Bytes
/
SwapProblem.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
class SwapProblem
{
public boolean solution(int[] arr)
{
boolean unsorted = false;
int unsortedIndex = -1;
int toSwapIndex = -1;
for(int i = 0; i < arr.length - 1; i++)
{
if(arr[i + 1] < arr[i])
{
unsorted = true;
unsortedIndex = i;
toSwapIndex = i + 1;
break;
}
}
if(unsorted == true)
{
for(int i = unsortedIndex + 1; i < arr.length - 1; i++)
{
if(arr[i + 1] < arr[i])
{
toSwapIndex = i + 1;
}
}
}
if(unsortedIndex != -1)
{
int temp = arr[unsortedIndex];
arr[unsortedIndex] = arr[toSwapIndex];
arr[toSwapIndex] = temp;
}
for(int i = 0; i < arr.length - 1; i++)
{
if(arr[i + 1] < arr[i])
{
return false;
}
}
return true;
}
public static void main(String args[])
{
SwapProblem swap = new SwapProblem();
int[] arr = {3, 2, 1};
boolean res = swap.solution(arr);
System.out.println(res);
}
}