Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort booleans, O(N) time, O(1) space

For a homework assignment, I am asked to sort an array of bools using a method that uses O(1) space, and O(N) time complexity. Can any hints be offered? I was thinking of something along the pivot method of a quicksort algorithm. -Thanks!

like image 645
bensherms Avatar asked Jan 27 '26 02:01

bensherms


2 Answers

  1. Keep an index at the front and back.
  2. check the current front index, if it's false increment the front index
  3. if it's true swap with the back index and decrement the back index
  4. continue with steps 2 and 3 until front and back indices are equal to each other
like image 162
aaronman Avatar answered Jan 30 '26 03:01

aaronman


If you have an array of booleans, you can simply count the true (or false) values. Lets assume this results to k. Then you set the first k elements of the array to true and the remaining false.

This algorithm iterates through the array twice (so it has an O(N) time complexity), and only uses one counter, so the space required is O(1).

like image 29
mcserep Avatar answered Jan 30 '26 04:01

mcserep



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!