forked from rampatra/Algorithms-and-Data-Structures-in-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSwappingInAnArray.java
41 lines (37 loc) · 957 Bytes
/
SwappingInAnArray.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
package com.hackerrank.contests;
/**
* @author rpatra16
* @since 04/11/2018
*/
public class SwappingInAnArray {
// Complete the swapToSort function below.
static int swapToSort(int[] a) {
// Return -1 or 0 or 1 as described in the problem statement.
int swaps = 0;
for (int i=0; i < a.length-1; i++) {
int swapIndex = i;
for (int j = i + 1; j < a.length; j++) {
if (a[i] > a[j]) {
swapIndex = j;
}
}
if (swapIndex != i) {
swap(a, i, swapIndex);
swaps++;
i--;
}
}
if (swaps > 1) {
return -1;
} else {
return swaps;
}
}
private static void swap(int[] a, int i, int j) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
public static void main(String[] args) {
}
}