Question: solve this puzzle? An array contains 4 occurences of 0s, 7 occurences of 1s and 9 occurences of 2s in any order. The array is to be sorted using only swap operations. What is the minimum number of swaps needed in the worst case to sort the array?

Answer: It the worst case, none of the 0's is in the correct place, so it will take 4 swaps to put them in the correct the first 4 slots of the array. That leaves you with 7 1s and 9 2s. It will take you 7 swaps to get the 1s into the correct positions. The worst case will look like: 11112222222221110000\n\nIn general if you have n objects in broken into subsets, it will take you minimum of n - (size of largest subset) exchanges to get them into position by swapping. Swap all the smaller subsets into position first, and the largest subset will end up in the correct position.
This question from the Yahoo Q&A forum is categorized in the topic: Entertainment & Music