wu :: forums
« wu :: forums - single traversal »

Welcome, Guest. Please Login or Register.
May 1st, 2025, 3:43am

RIDDLES SITE WRITE MATH! Home Home Help Help Search Search Members Members Login Login Register Register
   wu :: forums
   riddles
   cs
(Moderators: william wu, Eigenray, Icarus, ThudnBlunder, Grimbal, SMQ, towr)
   single traversal
« Previous topic | Next topic »
Pages: 1  Reply Reply Notify of replies Notify of replies Send Topic Send Topic Print Print
   Author  Topic: single traversal  (Read 754 times)
darklord
Newbie
*





   


Posts: 10
single traversal  
« on: Apr 9th, 2009, 5:48am »
Quote Quote Modify Modify

gn: an array of only 1's and 0's how to separate them such that 0's in left and 1's in rite.in a single traversal.with out using extra space.in o(n)
IP Logged
towr
wu::riddles Moderator
Uberpuzzler
*****



Some people are average, some are just mean.

   


Gender: male
Posts: 13730
Re: single traversal  
« Reply #1 on: Apr 9th, 2009, 6:01am »
Quote Quote Modify Modify

http://www.ocf.berkeley.edu/~wwu/cgi-bin/yabb/YaBB.cgi?board=riddles_cs; action=display;num=1213096186
IP Logged

Wikipedia, Google, Mathworld, Integer sequence DB
SMQ
wu::riddles Moderator
Uberpuzzler
*****






   


Gender: male
Posts: 2084
Re: single traversal  
« Reply #2 on: Apr 9th, 2009, 6:10am »
Quote Quote Modify Modify

Actually, since this statement of the problem doesn't require a stable sort, it's much simpler: initialize two pointers/indexes to the start and end of the array.  Scan towards the center, swapping pairs of misplaced 1's and 0's.  When the two meet, you're done.
 
Edit to add code:
 
#include <vector>
using namespace std;
 
enum binary { zero = 0, one = 1 };
 
void sort(vector<binary> arr) {
  int first = 0, last = arr.size() - 1;
  while (first < last) {
    while (first < last && arr[first] == binary::zero) ++first;
    while (first < last && arr[last] == binary::one) --last;
    if (first < last) {
      binary temp = arr[first]; arr[first] = arr[last]; arr[last] = temp;
    }
  }
}

--SMQ
« Last Edit: Apr 9th, 2009, 6:31am by SMQ » IP Logged

--SMQ

towr
wu::riddles Moderator
Uberpuzzler
*****



Some people are average, some are just mean.

   


Gender: male
Posts: 13730
Re: single traversal  
« Reply #3 on: Apr 9th, 2009, 6:23am »
Quote Quote Modify Modify

Well, I'm sure it's been asked before. The trouble is finding it. Besides, that thread does mention the solution that works here, because nearly everyone ignored the stable sort requirement in that thread.
« Last Edit: Apr 9th, 2009, 6:24am by towr » IP Logged

Wikipedia, Google, Mathworld, Integer sequence DB
Pages: 1  Reply Reply Notify of replies Notify of replies Send Topic Send Topic Print Print

« Previous topic | Next topic »

Powered by YaBB 1 Gold - SP 1.4!
Forum software copyright © 2000-2004 Yet another Bulletin Board