HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

Sorting an array of boolean values

Submitted by: @import:stackexchange-cs··
0
Viewed 0 times
arraysortingvaluesboolean

Problem

im looking for some guidance on how to get started with sorting an array of booleans so that the falses would be in front of the trues.

so if given this:
a = {true, true, false, true, false}

it would return:
a = {false, false, true, true, true}

here is the exact question:
Suppose you have an array of booleans of size n. Give an algorithm that sorts the array so that all false elements come before all true elements.

Thanks for any help you can give me!

Solution

With only 2 possible values, you want to use an algorithm such as Counting Sort.

Since you only have 2 possible values, true and false, it's easy to just count how many true/false values you have. But to be more efficient, you can just count how many trues you have (or falses) instead. Because size - numTrue = numFalse.

Context

StackExchange Computer Science Q#48417, answer score: 6

Revisions (0)

No revisions yet.