117k views
2 votes
You have an array of n data records to sort, each with a key of 0 or 1. An algorithm for sorting such a set of records might possess some subset of the following three desirable characteristics:

i. The algorithm runs in O(n) time.
ii. The algorithm is stable.
iii. The algorithm sorts in place, using no more than a constant amount of storage space in addition to the original array. Give an algorithm that satisfies criteria 1 and 2 above.

1 Answer

2 votes

Final answer:

Counting Sort is an algorithm that satisfies both the O(n) time complexity and stability criteria for sorting an array with keys of 0 or 1.

Step-by-step explanation:

An algorithm that satisfies both criteria 1 and 2 is Counting Sort. Counting Sort is a linear time sorting algorithm that can sort an array of n records with integer keys in the range from 0 to k, where k is a constant. Since the keys in this case are either 0 or 1, k is 1.

Counting Sort works by first counting the frequency of each key (0 or 1) in the input array, and then reconstructing the sorted array based on these counts. It is a stable sorting algorithm, meaning that records with the same key will appear in the same order in the sorted array as they do in the input array.

Counting Sort satisfies the first criterion since it runs in linear time, O(n), and it satisfies the second criterion since it is a stable sorting algorithm. However, it does not satisfy the third criterion since it requires additional storage space to store the counts of each key.

Counting sort is an integer sorting algorithm used in computer science to collect objects according to keys that are small positive integers.