javascript, Given an array of binary digits, 0 and 1, sort the array so that all zeros are at one end and all ones are at the other. Which end does not matter. To sort the array, swap any two adjacent elements. Determine the minimum number of swaps to sort the array.

Answer :

Answer:

# Python Code:-

def minMoves(list1):

list2=[]

n=len(list1) # Length of list.

for i in range(n):

list2.append(list1[i])

 

#Counting number of swaps when 0 is left side and 1 is right side.

count1=0

for i in range(0,n-1):

for j in range(0,n-i-1):

if list1[j]>list1[j+1]:

count1+=1

list1[j],list1[j+1]=list1[j+1],list1[j]

#Counting number of swaps when 1 is left side and 0 is right side.

count2=0

for i in range(0,len(list2)-1):

for j in range(0,len(list2)-i-1):

if list2[j]<list2[j+1]:

count2+=1

list2[j],list2[j+1]=list2[j+1],list2[j]

return min(count1,count2)

def main():

num=int(input())

list1=[]

for i in range(0,num):

temp=int(input())

list1.append(temp)

min_swap= minMoves(list1)

print("Output : ",min_swap)

if _name=="main_":

main()

Output:

${teks-lihat-gambar} tallinn
MrRoyal

The program is an illustration of loops.

Loops are used to perform repetitive and iterative operations.

The program in JavaScript, where comments are used to explain each line is as follows:

//This defines the function

function minSwap(myArr, n){

 //This initializes an array to store the count of zeroes

 let zeroCount = [];

 //This initializes i and count to 0

 let i,count = 0;

 //This following for loop counts the number of 0's after every 1.

 zeroCount[n - 1] = 1 - myArr[n - 1];

 for (int i = n - 2; i >= 0; i--){

  zeroCount[i] = zeroCount[i + 1];

  if (myArr[i] == 0)

   zeroCount[i]++;

 }

 //This following for loop counts the total number of swaps

 for (i = 0; i < n; i++){

  if (myArr[i] == 1)

   count += zeroCount[i];

 }

 //This returns the minimum number of swap

 return count;

}

Read more about similar programs at:

https://brainly.com/question/14943773

Other Questions