Ask Question
9 March, 12:07

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

}

+5
Answers (1)
  1. 9 March, 15:09
    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?
Get 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 & Technology if there is no answer or all answers are wrong, use a search bar and try to find the answer among similar questions.
Search for Other Answers