File tree 1 file changed +41
-0
lines changed
src/main/java/com/hackerrank/contests
1 file changed +41
-0
lines changed Original file line number Diff line number Diff line change
1
+ package com .hackerrank .contests ;
2
+
3
+ /**
4
+ * @author rpatra16
5
+ * @since 04/11/2018
6
+ */
7
+ public class SwappingInAnArray {
8
+ // Complete the swapToSort function below.
9
+ static int swapToSort (int [] a ) {
10
+ // Return -1 or 0 or 1 as described in the problem statement.
11
+ int swaps = 0 ;
12
+ for (int i =0 ; i < a .length -1 ; i ++) {
13
+ int swapIndex = i ;
14
+ for (int j = i + 1 ; j < a .length ; j ++) {
15
+ if (a [i ] > a [j ]) {
16
+ swapIndex = j ;
17
+ }
18
+ }
19
+ if (swapIndex != i ) {
20
+ swap (a , i , swapIndex );
21
+ swaps ++;
22
+ i --;
23
+ }
24
+ }
25
+ if (swaps > 1 ) {
26
+ return -1 ;
27
+ } else {
28
+ return swaps ;
29
+ }
30
+ }
31
+
32
+ private static void swap (int [] a , int i , int j ) {
33
+ int temp = a [i ];
34
+ a [i ] = a [j ];
35
+ a [j ] = temp ;
36
+ }
37
+
38
+ public static void main (String [] args ) {
39
+
40
+ }
41
+ }
You can’t perform that action at this time.
0 commit comments