Fidelity Question2:
You are given an array which you need to sort.
But Sorting here means different.Here by sorting we mean that if an array for example has following values:{3,4,2,9}, the resultant can be :
{4,2,3,9} OR {2,4,3,9} OR {4,2,9,3} OR {2,4,9,3}.
There are in total four different valid sorting resultants.
You need to find out the minimum number of moves to make an array sorted.
PS: (The question description is made easier than the original one)
Explanation: The question, in fact, needs that you move all the even elements on the left side of the array and all the odd elements on the right side but with the minimum number of moves.
Implementation:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package hackerrankQuestion.fidelity; | |
import java.util.Scanner; | |
public class Solution2 | |
{ | |
public static void main(String[] args) | |
{ | |
Scanner sc = new Scanner(System.in); | |
int numberOfElements = sc.nextInt(); | |
int ar[] = new int[numberOfElements]; | |
for (int i = 0; i < numberOfElements; i++) | |
{ | |
ar[i] = sc.nextInt(); | |
} | |
int numberOfMoves = minMoves(ar); | |
System.out.println("The minimum number of moves is " + numberOfMoves); | |
for (int i : ar) | |
{ | |
System.out.println(i); | |
} | |
} | |
public static int minMoves(int ar[]) | |
{ | |
int beg = 0; | |
int end = ar.length - 1; | |
int count = 0; | |
while (beg <= end) | |
{ | |
if (ar[beg] % 2 != 0 && ar[end] % 2 == 0) | |
{ | |
int x = ar[beg]; | |
ar[beg] = ar[end]; | |
ar[end] = x; | |
beg++; | |
end--; | |
count++; | |
} | |
if (ar[beg] % 2 == 0) | |
{ | |
beg++; | |
} | |
if (ar[end] % 2 != 0) | |
{ | |
end--; | |
} | |
} | |
return count; | |
} | |
} |