Consider an array of size n. The values of the array are either 0 or 1.

Share

Consider an array of size n. The values of the array are either 0 or 1.Write a program to move zeros to the beginning and all ones to the end in the same array without using an extra array.

input: arr[] = {1, 0, 1, 0, 0, 1}

output: arr[] = {0, 0, 0, 1, 1, 1} 


Solution in python

def move(ar=[1,0,1,1 ,0, 1, 0, 0, 1,0,0]):
    for i in range(ar.count(1)):
        index_of_1 = ar.index(1)  # find the index of the first occurrence of 1
        ar.append(ar.pop(index_of_1)) #add all ones to the end of array/list
    return ar

>>>[0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1] #output
        

Share
Related  write a code in HTML for form that send input text string from the same page

Leave a Reply

Your email address will not be published. Required fields are marked *

Top 5 Most Expensive Domains Ever Sold 4 Must-Try ChatGPT Alternatives: Perplexity AI, BardAI, Pi, and More! Types of Trading Techniques in the Stock Market. ChatGPT app now available in India this AI chatbot can help you make your life more productive. What is wrong with following function code?