Ask Question
20 October, 10:47

In an array, we can swap the elements at any two indices in a single operation called a move. For example, if our array is a = {17, 4, 8}, we can swap a0 = 17 and a2 = 8 to get a = {8,4,17} in a single move. We want to custom-sort an array such that all of the even elements are at the beginning of the array and all of the odd elements are at the end of the array.

Complete the function moves. The function must return the minimum of the moves it takes to sort an array of integers with all even elements at earlier indexes that any odd element.

Note: the order of the elements within even or odd doesn't matter

Sample input 4,13,10,21,20

Sample output 1

In jа vascript

function moves (a) {

//you code here

}

+4
Answers (1)
  1. 20 October, 13:07
    0
    function moves (a) {

    var left = 0;

    var right = a. length-1;

    var count = 0;

    while (left < right) {

    if (a[left] % 2 = = 0) {

    left++;

    continue;

    }

    if (a[right] % 2 = = 1) {

    right--;

    continue;

    }

    var temp = a[left];

    a[left] = a[right];

    a[right] = temp;

    left++;

    right--;

    count++;

    }

    return count;

    }

    var a = [4,13,10,21,20];

    console. log ('Number of moves: ' + moves (a));

    console. log ('Sorted array: ' + a);
Know the Answer?
Not Sure About the Answer?
Find an answer to your question ✅ “In an array, we can swap the elements at any two indices in a single operation called a move. For example, if our array is a = {17, 4, 8}, ...” in 📘 Computers and Technology if you're in doubt about the correctness of the answers or there's no answer, then try to use the smart search and find answers to the similar questions.
Search for Other Answers