Close

Sorting the array of 0,1,2's

We have an array that contains only 0, 1 and 2. We have to write a program to sort this array.For example if the input array is [2,0,1,2,1,0,0,2], the output should be[0,0,0,1,1,2,2,2].As the first thought, we can very well use well known sorting algorithms like Quick sort, or Merge sort or Heap sort. But that…

Sorting binary array

Given an array of 0s and 1s, how do we sort them? After sorting all the 0s appear before all the 1s.For example the array [0,1,0,1,1,0,0,0,1,1] becomes [0,0,0,0,0,1,1,1,1,1]Let us look at two approaches to solve this problem. The first one is based on bucket sort and the second is more intelligent.Method#1:We can take two counts…

Check if an array has duplicate numbers

Given an array numbers, how do we write a function checkDuplicates() which returns true if the array has at least one element repeated; returns false if all the elements are unique. We discuss three different implementations of this function with various time and space complexities. Method-1: Naive approach This approach checks every possible pair in…

Finding the median of an array

Median of an array is defined as the middle element when it is sorted. The middle element is the one which divides the array into two equal halves if the array is of odd length. If the length is even, the average of two middle elements is median.For example the median of [4,3,2,5,1] is 3…

Program to shuffle an array

In some applications like card games, we need to shuffle an array of objects. In this post we will consider the problem of shuffling an array of numbers so that the same algorithm would be applicable for any type of arrays. We use the random number generator in this algorithm. Let us consider an array…