Jump to content
  • Advertisement
Sign in to follow this  
TEUTON

which sorting

This topic is 4502 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

suppose i have an array with elements as 0 and 1 only. What will be the best way(running time) to sort it. I thought about adding all elements and then filling arrays with no of 0's and then 1's. Is there any better method than this??

Share this post


Link to post
Share on other sites
Advertisement
You have a O(n) algorithm, it can't get any better than that in terms of time complexity.

This is how I would do it (assuming C++)

void sort(int* p, int size)
{
int* q = p;

while ( size-- != 0 )
{
if ( !*p++ )
{
*q++ = 0;
}
}

while ( p != q )
{
*q++ = 1;
}
}


Two pointers are kept, one (p) scans over the entire array, and each time it encounters a 0, a 0 is written at *q, and q is moved one position to the right. After p has scanned over the entire array, q is used to change all remaining elements to 1.

Share this post


Link to post
Share on other sites
I guess my algorithm requires O(2n) time...isn't it



for(i=0;i<size;i++)
{
num += arr;
}


for(i=0;i<size-num;i++)
{
arr =0;
}

for(i=num;i<size;i++)
{
arr =1;
}



Share this post


Link to post
Share on other sites
In a way, yes. But as far as I know, people consider O(n) = O(2n).
The algorithm I posted is O(2n) as well.

I wouldn't know which one of our algorithms performs better in practice.

Share this post


Link to post
Share on other sites
I profiled it with only 10 elements

Time taken little more than 3 ms -My Version
Time Taken apprx 9 ms -Your version

Share this post


Link to post
Share on other sites
Usually, for profiling to be accurate, you should test with various array's size (and a lot bigger than 10 elements)

- edit

And different array's setup (already sorted, 1-0-1-0-1-0..., random, etc.) to test worse case / best case scenarios!

Share this post


Link to post
Share on other sites
With 10000000 elements, using patterns [1,0,1,0,...], [1,1,1,...,0,0,0,...], [0,0,0,...,1,1,1,...] and [0,0,0,0,...], my version is faster, but not by much. Yours is faster with [1,1,1,1,...].

(Not that this way of benchmarking is in any way accurate...)

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!