<?xml version='1.0' encoding='UTF-8'?><?xml-stylesheet href="http://www.blogger.com/styles/atom.css" type="text/css"?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:blogger='http://schemas.google.com/blogger/2008' xmlns:georss='http://www.georss.org/georss' xmlns:gd="http://schemas.google.com/g/2005" xmlns:thr='http://purl.org/syndication/thread/1.0'><id>tag:blogger.com,1999:blog-2282836992153344714</id><updated>2024-09-05T01:33:32.059-07:00</updated><category term="algorithm"/><category term="puzzle"/><category term="array"/><category term="C++"/><category term="trees"/><category term="linked lists"/><category term="strings"/><category term="Bit Manipulation"/><category term="sort"/><category term="data structures"/><category term="programming"/><category term="mathematics"/><category term="search"/><category term="operating systems"/><category term="todo"/><category term="unix"/><category term="Elementary Combinatorics"/><category term="heap"/><category term="merge"/><category term="numbers"/><category term="permutations"/><category term="probability"/><category term="stack"/><category term="class"/><category term="palindrome"/><category term="queue"/><category term="sorting"/><category term="stacks"/><category term="system programming"/><category term="Computer Science"/><category term="Matrix"/><category term="STL"/><category term="YCbCr"/><category term="YPbPr"/><category term="YUV"/><category term="aptitude"/><category term="audio video engineering"/><category term="codec"/><category term="color space"/><category term="graph"/><category term="knuth"/><category term="lateral thinking"/><category term="logic"/><category term="maxmin"/><category term="memory"/><category term="prime numbers"/><category term="python"/><category term="quicksort"/><category term="taocp"/><category term="virtual functions"/><title type='text'>The Algo Blog</title><subtitle type='html'>Blog on algorithms, puzzles, programming .... musings of a computer engineer.</subtitle><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://the-algo-blog.blogspot.com/feeds/posts/default'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/2282836992153344714/posts/default?redirect=false'/><link rel='alternate' type='text/html' href='http://the-algo-blog.blogspot.com/'/><link rel='hub' href='http://pubsubhubbub.appspot.com/'/><link rel='next' type='application/atom+xml' href='http://www.blogger.com/feeds/2282836992153344714/posts/default?start-index=26&amp;max-results=25&amp;redirect=false'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><generator version='7.00' uri='http://www.blogger.com'>Blogger</generator><openSearch:totalResults>181</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>25</openSearch:itemsPerPage><entry><id>tag:blogger.com,1999:blog-2282836992153344714.post-8898974935160763460</id><published>2011-07-31T00:58:00.000-07:00</published><updated>2011-07-31T01:21:03.023-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="operating systems"/><title type='text'>relocatable address</title><content type='html'>The address generated by the compiler are relocatable addresses.&lt;br /&gt;
See : &lt;i&gt;Introduction to computer-based imaging systems&lt;/i&gt; By Divyendu Sinha, Edward R. Dougherty , &lt;a href=&quot;http://books.google.co.in/books?id=NLpAggmyp3EC&amp;lpg=PA213&amp;dq=relocatable%20address&amp;pg=PA213#v=onepage&amp;f=false&quot;&gt;page.213&lt;/a&gt; :&lt;br /&gt;
&lt;blockquote&gt;Assuming the page size as 64 KB (2&lt;sup&gt;16&lt;/sup&gt;):&lt;br /&gt;
The compiler generated relocatable addresses as if the entire program were to be loaded at once. The page number and offset can be easily computed from the relocatable address. Since the offset must be a nonnegative number smaller than the page size, the offset is the least significant 16 bits of the relocatable address. The remaining 25-16 = 9 bits specify the page number. Consider the relocatable address 145678. Since&lt;br /&gt;
&lt;br /&gt;
145678 (decimal) = 0 00000010 00111001 00001110 (binary),&lt;br /&gt;
we have the page number as 2 (or 000000010 in binary) and the offset as 14,606( or 0011100100001110 in binary).&lt;br /&gt;
&lt;br /&gt;
If the page size is changed later on to 32KB, programs need not be recompiled to run on the system. Computation of page number and offset is done by the memory manager&lt;br /&gt;
&lt;/blockquote&gt;</content><link rel='replies' type='application/atom+xml' href='http://the-algo-blog.blogspot.com/feeds/8898974935160763460/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/2282836992153344714/8898974935160763460' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/2282836992153344714/posts/default/8898974935160763460'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/2282836992153344714/posts/default/8898974935160763460'/><link rel='alternate' type='text/html' href='http://the-algo-blog.blogspot.com/2011/07/relocatable-address.html' title='relocatable address'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-2282836992153344714.post-2780102558705216258</id><published>2011-07-23T23:51:00.000-07:00</published><updated>2011-07-23T23:51:08.801-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="probability"/><title type='text'>Basic introduction to probability</title><content type='html'>Surprisingly the basic introduction to probability was found in a biology book!&lt;br /&gt;
Here is the summary:&lt;br /&gt;
Product Rule:&lt;br /&gt;
When two or more events are independent, the probability that they will occur in succession is calculated using the product rule--their individual probabilities are multiplied. Ex : probability of getting two heads in succession is 1/2 x 1/2 = 1/4&lt;br /&gt;
&lt;br /&gt;
Sum Rule:&lt;br /&gt;
Sum Rule is applied when there are two or more different ways of obtaining the same outcome; that is, the probability tat either event A or event B will occur equals P(A) + P(B)&lt;br /&gt;
&lt;br /&gt;
Source: Billogy: Te dynamic science by Peter Russell &lt;a href=&quot;http://books.google.co.in/books?id=S9IRCnDMmY8C&amp;lpg=PA240&amp;dq=two%20coin%20toss%20probability&amp;pg=PA240#v=onepage&amp;q&amp;f=false&quot;&gt;p.240&lt;/a&gt;</content><link rel='replies' type='application/atom+xml' href='http://the-algo-blog.blogspot.com/feeds/2780102558705216258/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/2282836992153344714/2780102558705216258' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/2282836992153344714/posts/default/2780102558705216258'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/2282836992153344714/posts/default/2780102558705216258'/><link rel='alternate' type='text/html' href='http://the-algo-blog.blogspot.com/2011/07/basic-introduction-to-probability.html' title='Basic introduction to probability'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-2282836992153344714.post-3128046242430151869</id><published>2011-07-23T23:38:00.000-07:00</published><updated>2011-07-23T23:38:31.379-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="linked lists"/><title type='text'>reversing a linked list</title><content type='html'>Few of the most elegant solutions for reversing a linked list:&lt;br /&gt;
1. Stanford : &lt;a href=&quot;http://cslibrary.stanford.edu/105/LinkedListProblems.pdf&quot;&gt;Linked list problems&lt;/a&gt;&lt;br /&gt;
2. &lt;i&gt;Algorithms : 4th Edition&lt;/i&gt; : &lt;a href=&quot;http://introcs.cs.princeton.edu/java/43stack/&quot;&gt;Stacks and Queues&lt;/a&gt;&lt;br /&gt;
The code is reproduced here and is very elegant:&lt;br /&gt;
&lt;pre&gt;public Node reverse(Node first) {
    if (first == null || first.next == null) return first;
    Node second = first.next;
    Node rest = reverse(second);
    second.next = first;
    first.next  = null;
    return rest;
}
&lt;/pre&gt;</content><link rel='replies' type='application/atom+xml' href='http://the-algo-blog.blogspot.com/feeds/3128046242430151869/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/2282836992153344714/3128046242430151869' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/2282836992153344714/posts/default/3128046242430151869'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/2282836992153344714/posts/default/3128046242430151869'/><link rel='alternate' type='text/html' href='http://the-algo-blog.blogspot.com/2011/07/reversing-linked-list.html' title='reversing a linked list'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-2282836992153344714.post-3757131341818599852</id><published>2011-07-23T05:16:00.000-07:00</published><updated>2011-07-23T05:16:45.920-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="algorithm"/><category scheme="http://www.blogger.com/atom/ns#" term="data structures"/><category scheme="http://www.blogger.com/atom/ns#" term="queue"/><category scheme="http://www.blogger.com/atom/ns#" term="stack"/><title type='text'>Implementing stack using queues and vice versa</title><content type='html'>To implement stack using queues, with two cases : constant insertion time, linear removal time and vice-a-versa, see this &lt;a href=&quot;http://stackoverflow.com/questions/688276/implement-stack-using-two-queues/688299#688299&quot;&gt;stack overflow discussion&lt;/a&gt;&lt;br /&gt;
&lt;br /&gt;
To implement a queue using two stacks,&lt;br /&gt;
&lt;pre&gt;// Basic solution
class Queue
{
    Stack s1; // used as main stack
    Stack s2; // used as stack for temp storage
    
    enqueue(T&amp; t)
    {
        if ( !s1.empty() ) s1.push(t);
        else  s2.push(t);
    }

    T dequeue()
    {
        T t;
        if ( s1.isEmpty() &amp;&amp; s2.isEmpty() ) throw Exception();
        return __dequeue(s1,s2);
    }
    T __dequeue(Stack&amp; from, Stack&amp; to) 
    {
        size_t n = from.count();
        if (!n) return __dequeue(to, from);
        move(from, to, n-1);
        t = from.pop();
        move(to, from, n-1);
        return t;
    }
}

// optimized solution : by saving the last operation
class Queue
{
    Stack s1; // used as main stack
    Stack s2; // used as stack for temp storage
    
    enqueue(T&amp; t)
    {
        if ( last_operation == Dequeue ) 
            move( s2,s1);
        s1.push(t);
        last_operation = Enqueue;
    }

    T dequeue()
    {
        if ( s1.isEmpty() &amp;&amp; s2.isEmpty() ) throw Exception();
        // if the last operation was dequeue, the required element
        // is already on the temp usage stack s2
        if ( last_operation == Dequeue )
            return s2.pop();

        T t= __dequeue(s1,s2);
        last_operation = Dequeue;
    }
    T __dequeue(Stack&amp; from, Stack&amp; to) 
    {
        size_t n = from.count();
        if (!n) return __dequeue(to, from);
        move(from, to, n-1);
        t = from.pop();
        move(to, from, n-1);
        return t;
    }
}
&lt;/pre&gt;&lt;br /&gt;
Also there is a interesting solution in &lt;a href=&quot;http://books.google.co.in/books?id=3Iw50opbTfcC&amp;pg=PA90&amp;dq=implement+queue+using+two+stacks&amp;hl=en&amp;ei=ZKkqTpiQHcLXrQe8v5WyDQ&amp;sa=X&amp;oi=book_result&amp;ct=result&amp;resnum=10&amp;ved=0CFoQ6AEwCQ&quot;&gt;Algorithms and Programming: Problems and Solutions - Page 90&lt;/a&gt;&lt;br /&gt;
&lt;blockquote&gt;We maintain the following invariant relation: stacks whose bottoms are&lt;br /&gt;
put together, form the queue. (In other words, listing all elements of one stack from&lt;br /&gt;
top to bottom and then of the other stack from bottom to top, we list all the queue&lt;br /&gt;
elements in the proper order.) To add an element to the queue, it is enough to add it to&lt;br /&gt;
one of the stacks. To check if the queue is empty, we must check that both stacks are&lt;br /&gt;
empty. When taking the first element from the queue, we should distinguish between&lt;br /&gt;
two cases. If the stack that contains the first element is not empty, there is no problem.&lt;br /&gt;
If that stack is empty, the required element is buried under all the elements of the&lt;br /&gt;
second stack. In this case, we move all the elements one-by-one onto the first stack&lt;br /&gt;
(their ordering is reversed) and return to the first case.&lt;br /&gt;
The number of operations for this step is not limited by any constant. However,&lt;br /&gt;
the requirement posed in the problem is still met. Indeed, any element of the queue&lt;br /&gt;
can participate in such a process at most once during its presence in the queue.&lt;br /&gt;
&lt;/blockquote&gt;</content><link rel='replies' type='application/atom+xml' href='http://the-algo-blog.blogspot.com/feeds/3757131341818599852/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/2282836992153344714/3757131341818599852' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/2282836992153344714/posts/default/3757131341818599852'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/2282836992153344714/posts/default/3757131341818599852'/><link rel='alternate' type='text/html' href='http://the-algo-blog.blogspot.com/2011/07/implementing-stack-using-queues-and.html' title='Implementing stack using queues and vice versa'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-2282836992153344714.post-5546357347162529471</id><published>2011-07-22T23:03:00.000-07:00</published><updated>2011-07-22T23:03:23.055-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="mathematics"/><title type='text'>f(f(n)) = -n</title><content type='html'>Originally from &lt;a href=&quot;http://stackoverflow.com/questions/731832/interview-question-ffn-n&quot;&gt;stackoverflow&lt;/a&gt;&lt;br /&gt;
While working on this puzzle, became confused, but this can be simplified if we first write the state diagram and then the code. The state diagram should consider odd/even and +ve/-ve numbers.&lt;br /&gt;
A simple control flow can be as follows:&lt;br /&gt;
A: 1 &amp;rarr; 2&lt;br /&gt;
B: 2 &amp;rarr; -1&lt;br /&gt;
C: -1 &amp;rarr; -2&lt;br /&gt;
D: -2 &amp;rarr; 1&lt;br /&gt;
E: 1 &amp;rarr; 2&lt;br /&gt;
&lt;br /&gt;
Notice that E and A are same.&lt;br /&gt;
Once we have this, &lt;br /&gt;
&lt;pre&gt;if n is +ve:
   if n is odd : return n+1
   if n is even : return -1* (n-1)
else if n is -ve:
   if n is odd : return n-1
   if n is even : return -1 * (n+1)
&lt;/pre&gt;&lt;br /&gt;
We get the highest rated &lt;a href=&quot;http://stackoverflow.com/questions/731832/interview-question-ffn-n/731912#731912&quot;&gt;solution &lt;/a&gt;on stackoverflow.</content><link rel='replies' type='application/atom+xml' href='http://the-algo-blog.blogspot.com/feeds/5546357347162529471/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/2282836992153344714/5546357347162529471' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/2282836992153344714/posts/default/5546357347162529471'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/2282836992153344714/posts/default/5546357347162529471'/><link rel='alternate' type='text/html' href='http://the-algo-blog.blogspot.com/2011/07/ffn-n.html' title='f(f(n)) = -n'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-2282836992153344714.post-3605873485776889921</id><published>2011-07-16T22:54:00.000-07:00</published><updated>2011-07-16T22:54:16.795-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="python"/><category scheme="http://www.blogger.com/atom/ns#" term="sorting"/><title type='text'>Sorting and array of 0 and 1&#39;s in single pass</title><content type='html'>Question from Princeton.edu&#39;s &lt;a href=&quot;http://introcs.cs.princeton.edu/java/42sort/&quot;&gt;sorting and searching &lt;/a&gt; :&lt;br /&gt;
&lt;blockquote&gt;Partitioning. Write a static method that sorts a Comparable array that is known to have at most two different values.&lt;br /&gt;
&lt;br /&gt;
Hint: Maintain two pointers, one starting at the left end and moving right, the other starting at the right end and moving left. Maintain the invariant that all elements to the left of the left pointer are equal to the smaller of the two values and all elements to the right of the right pointer are equal to the larger of the two values.&lt;/blockquote&gt;&lt;br /&gt;
Solution in python:&lt;br /&gt;
&lt;pre&gt;&quot;&quot;&quot;
Sort an array of 0&#39;s and 1&#39;s

Loop invariant
[0 0 0 0 0 0 |----unknown-----| 1 1 1 1 1 1]
             i                j
All elements &lt; i are 0
All element &gt; j are 1
elements between i and j are unknown.
&quot;&quot;&quot;

a1 = [ 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1]
a2 = [ 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0]
a3 = [ 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0 ]

def sort_01(a):
    i=0
    j=len(a)-1
    while i &lt; j:
        while i &lt; j and (a[i] &lt; a[j] or a[i]==0): i += 1
        while i &lt; j and a[i] &lt;= a[j]: j -= 1
        if i &lt; j: a[i],a[j] = 0,1
    print(a)

sort_01(a1)
sort_01(a2)
sort_01(a3)
&lt;/pre&gt;</content><link rel='replies' type='application/atom+xml' href='http://the-algo-blog.blogspot.com/feeds/3605873485776889921/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/2282836992153344714/3605873485776889921' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/2282836992153344714/posts/default/3605873485776889921'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/2282836992153344714/posts/default/3605873485776889921'/><link rel='alternate' type='text/html' href='http://the-algo-blog.blogspot.com/2011/07/sorting-and-array-of-0-and-1s-in-single.html' title='Sorting and array of 0 and 1&#39;s in single pass'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-2282836992153344714.post-5022885422398610293</id><published>2011-07-16T08:23:00.000-07:00</published><updated>2011-07-16T08:23:34.329-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="C++"/><category scheme="http://www.blogger.com/atom/ns#" term="STL"/><title type='text'>importance of  vector::reserve</title><content type='html'>Not using reserve results in quite some extra work.&lt;br /&gt;
&lt;pre&gt;
struct Foo
{
 static int i ;
 int f;
 Foo():f(i++){ cout &lt;&lt; &quot;in ctor:&quot; &lt;&lt; i &lt;&lt; endl; }
 Foo(const Foo&amp;):f(i++){ cout &lt;&lt; &quot;in copy ctor:&quot; &lt;&lt; i &lt;&lt; endl; }
};
int Foo::i = 1;

void tst_vec()
{
 vector&lt;Foo&gt; v;
 v.reserve(10);
 Foo f ;
 v.push_back(f);
 v.push_back(Foo());
 v.push_back(Foo());
 cout &lt;&lt; &quot;---&quot; &lt;&lt; endl;
 Foo&amp; temp = v[0];
}

---

with reserve:
in ctor:2
in copy ctor:3
in ctor:4
in copy ctor:5
in ctor:6
in copy ctor:7
---

without reserve:
in ctor:2
in copy ctor:3
in ctor:4
in copy ctor:5
in copy ctor:6
in ctor:7
in copy ctor:8
in copy ctor:9
in copy ctor:10


&lt;/pre&gt;</content><link rel='replies' type='application/atom+xml' href='http://the-algo-blog.blogspot.com/feeds/5022885422398610293/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/2282836992153344714/5022885422398610293' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/2282836992153344714/posts/default/5022885422398610293'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/2282836992153344714/posts/default/5022885422398610293'/><link rel='alternate' type='text/html' href='http://the-algo-blog.blogspot.com/2011/07/importance-of-vectorreserve.html' title='importance of  vector::reserve'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-2282836992153344714.post-1967427668528630179</id><published>2011-07-16T08:21:00.000-07:00</published><updated>2011-07-16T08:21:59.145-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="C++"/><title type='text'>virtual destructors and valgrind</title><content type='html'>Was curious to know the effects of missing a virtual destructor, and ran the program on valgrind:&lt;br /&gt;
&lt;br /&gt;
Valgrind reported a memory leak.&lt;br /&gt;
&lt;br /&gt;
&lt;pre&gt;user@ubuntu:~/devel/effective_cpp$ g++ virt_dtor.cpp -ggdb
user@ubuntu:~/devel/effective_cpp$ cat virt_dtor.cpp 
#include &lt;iostream&gt;
using namespace std;

class Base{
    public:
    ~Base() { cout &lt;&lt; &quot;~Base()&quot; &lt;&lt; endl; }
};

class Der: public Base{
    public:
        int* array;
     Der(){ array = new int[10]; }
    ~Der() { cout &lt;&lt; &quot;~Der()&quot; &lt;&lt; endl; delete[] array; }
};

int main()
{
    Base* b  = new Der;
    delete b;
}
user@ubuntu:~/devel/effective_cpp$ valgrind --leak-check=full ./a.out 
==2791== Memcheck, a memory error detector
==2791== Copyright (C) 2002-2010, and GNU GPL&#39;d, by Julian Seward et al.
==2791== Using Valgrind-3.6.0.SVN-Debian and LibVEX; rerun with -h for copyright info
==2791== Command: ./a.out
==2791== 
~Base()
==2791== 
==2791== HEAP SUMMARY:
==2791==     in use at exit: 40 bytes in 1 blocks
==2791==   total heap usage: 2 allocs, 1 frees, 44 bytes allocated
==2791== 
==2791== 40 bytes in 1 blocks are definitely lost in loss record 1 of 1
==2791==    at 0x4025FE5: operator new[](unsigned int) (vg_replace_malloc.c:299)
==2791==    by 0x80488C8: Der::Der() (virt_dtor.cpp:12)
==2791==    by 0x80487A7: main (virt_dtor.cpp:18)
==2791== 
==2791== LEAK SUMMARY:
==2791==    definitely lost: 40 bytes in 1 blocks
==2791==    indirectly lost: 0 bytes in 0 blocks
==2791==      possibly lost: 0 bytes in 0 blocks
==2791==    still reachable: 0 bytes in 0 blocks
==2791==         suppressed: 0 bytes in 0 blocks
==2791== 
==2791== For counts of detected and suppressed errors, rerun with: -v
==2791== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 19 from 8)


&lt;/pre&gt;</content><link rel='replies' type='application/atom+xml' href='http://the-algo-blog.blogspot.com/feeds/1967427668528630179/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/2282836992153344714/1967427668528630179' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/2282836992153344714/posts/default/1967427668528630179'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/2282836992153344714/posts/default/1967427668528630179'/><link rel='alternate' type='text/html' href='http://the-algo-blog.blogspot.com/2011/07/virtual-destructors-and-valgrind.html' title='virtual destructors and valgrind'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-2282836992153344714.post-4883025634413946182</id><published>2011-07-12T08:24:00.000-07:00</published><updated>2011-07-12T08:24:14.345-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="operating systems"/><title type='text'>Different types of mutexes</title><content type='html'>Some of the different types of Mutex:&lt;br /&gt;
-- Fair / Unfair Mutex : A mutex which allows access in the order of locking&lt;br /&gt;
-- Reentrant : which allows recursive locking, helpful when there are recursive calls in the code. See also man page description of &lt;a href=&quot;http://pubs.opengroup.org/onlinepubs/007908799/xsh/pthread_mutex_lock.html&quot;&gt;PTHREAD_MUTEX_RECURSIVE&lt;/a&gt;&lt;br /&gt;
-- Scalable Mutex&lt;br /&gt;
-- Sleep or spin : spin is optimal for short waits and sleep for long waits. And also while spining, there is no need for context switch.&lt;br /&gt;
&lt;br /&gt;
Reference : Intel threading building blocks: outfitting C++ for multi-core processor ... By James Reinders,&lt;a href=&quot;http://books.google.com/books?id=do86P6kb0msC&amp;lpg=PA115&amp;dq=reentrant%20mutex%20usage&amp;pg=PA115#v=onepage&amp;q&amp;f=false&quot;&gt; p.114&lt;/a&gt;</content><link rel='replies' type='application/atom+xml' href='http://the-algo-blog.blogspot.com/feeds/4883025634413946182/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/2282836992153344714/4883025634413946182' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/2282836992153344714/posts/default/4883025634413946182'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/2282836992153344714/posts/default/4883025634413946182'/><link rel='alternate' type='text/html' href='http://the-algo-blog.blogspot.com/2011/07/different-types-of-mutexes.html' title='Different types of mutexes'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-2282836992153344714.post-2564575981974606835</id><published>2011-07-10T03:02:00.001-07:00</published><updated>2011-07-10T03:02:50.419-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="C++"/><category scheme="http://www.blogger.com/atom/ns#" term="strings"/><title type='text'>reversing a string in C++</title><content type='html'>C++ string does not have reverse member function, &lt;br /&gt;
this is how we can do it:&lt;br /&gt;
&lt;pre&gt;string s(&quot;abcdef&quot;);
reverse(s.begin(), s.end());
&lt;/pre&gt;</content><link rel='replies' type='application/atom+xml' href='http://the-algo-blog.blogspot.com/feeds/2564575981974606835/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/2282836992153344714/2564575981974606835' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/2282836992153344714/posts/default/2564575981974606835'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/2282836992153344714/posts/default/2564575981974606835'/><link rel='alternate' type='text/html' href='http://the-algo-blog.blogspot.com/2011/07/reversing-string-in-c.html' title='reversing a string in C++'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-2282836992153344714.post-892292699682443314</id><published>2011-07-05T08:21:00.000-07:00</published><updated>2011-07-05T08:21:05.014-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="data structures"/><category scheme="http://www.blogger.com/atom/ns#" term="search"/><category scheme="http://www.blogger.com/atom/ns#" term="strings"/><title type='text'>Binary Search of a string</title><content type='html'>Interesting problem : How can we apply binary search to search a string in a big word file?&lt;br /&gt;
&lt;br /&gt;
We use a &lt;a href=&quot;http://en.wikipedia.org/wiki/Suffix_array&quot;&gt;suffix array &lt;/a&gt;and sort this array. Once sorted, we apply binary search on this array. See Bentley &lt;i&gt;Programming Pearls&lt;/i&gt; p.172. See also : &lt;i&gt;Large-scale genome sequence processing&lt;/i&gt; By Masahiro Kasahara, Shinichi Morishita, &lt;a href=&quot;http://books.google.com/books?id=r0_rAZmneyAC&amp;lpg=PA56&amp;dq=binary%20search%20string%20suffix%20array&amp;pg=PA56#v=onepage&amp;q=binary%20search%20string%20suffix%20array&amp;f=false&quot;&gt;p.56&lt;/a&gt;&lt;br /&gt;
&lt;br /&gt;
We can optimize this even further by storing the radix representation of strings (see:Cormen&#39;s section in Hashing) and the problem will be reduced to binary search of numbers.</content><link rel='replies' type='application/atom+xml' href='http://the-algo-blog.blogspot.com/feeds/892292699682443314/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/2282836992153344714/892292699682443314' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/2282836992153344714/posts/default/892292699682443314'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/2282836992153344714/posts/default/892292699682443314'/><link rel='alternate' type='text/html' href='http://the-algo-blog.blogspot.com/2011/07/binary-search-of-string.html' title='Binary Search of a string'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-2282836992153344714.post-5178417912145555545</id><published>2011-07-01T02:05:00.000-07:00</published><updated>2011-07-01T02:05:55.513-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="C++"/><title type='text'>C++ : non-local static object initialization problem</title><content type='html'>If one global object is directly dependent on another global object, the order of their construction is undefined. The best solution for it, suggested by Scott Meyers is to use singletons : ( see : Scott Meyers &quot;Item 47: Ensure that non-local static objects are initialized before they&#39;re used.&quot; &lt;i&gt;Effective C++&lt;/i&gt; )&lt;br /&gt;
&lt;tt&gt;&lt;br /&gt;
The basis of this approach is the observation that although C++ says next to nothing about when a nonlocal static object is initialized, it specifies quite precisely when a static object inside a function (i.e. a local static object) is initialized: it&#39;s when the object&#39;s definition is first encountered during a call to that function. So if you replace direct accesses to non-local static objects with calls to functions that return references to local static objects inside them, you&#39;re guaranteed that the references you get back from the functions will refer to initialized objects. As a bonus, if you never call a function emulating a nonlocal&lt;br /&gt;
static object, you never incur the cost of constructing and destructing the object, something that can&#39;t be said for true non-local static objects&lt;br /&gt;
&lt;/tt&gt;</content><link rel='replies' type='application/atom+xml' href='http://the-algo-blog.blogspot.com/feeds/5178417912145555545/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/2282836992153344714/5178417912145555545' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/2282836992153344714/posts/default/5178417912145555545'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/2282836992153344714/posts/default/5178417912145555545'/><link rel='alternate' type='text/html' href='http://the-algo-blog.blogspot.com/2011/07/c-non-local-static-object.html' title='C++ : non-local static object initialization problem'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-2282836992153344714.post-4349976603807268691</id><published>2011-07-01T00:26:00.000-07:00</published><updated>2011-07-01T00:33:07.027-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="C++"/><title type='text'>Multiple Inheritance : Overriding same named functions in derived.</title><content type='html'>Technique for overriding same named functions in Base classes in a multiple inheritance: ( See : Item 43 in &lt;i&gt;Effective C++&lt;/i&gt; , see also, Exceptional C++ )&lt;br /&gt;
&lt;br /&gt;
&lt;pre&gt;#include &lt; iostream &gt;
using namespace std;

class Base1{
    public:
    virtual int func(){ cout &lt;&lt; &quot;base1::func&quot; &lt;&lt; endl; }
};

class Base2{
    public:
    virtual int func(){ cout &lt;&lt; &quot;base2::func&quot; &lt;&lt; endl; }
};

class Der : public Base1, public Base2
{
    public:
    // overrides both Base1, and Base func
    virtual int func() { cout &lt;&lt; &quot;der::func&quot; &lt;&lt; endl; }
};

/** Using auxillary classes  */
class AuxBase1: public Base1{
    public:
        virtual int base1_func() = 0;
        virtual int func() {return base1_func(); }
};
class AuxBase2: public Base2{
    public:
        virtual int base2_func() = 0;
        virtual int func() {return base2_func(); }
};

class Der2 : public AuxBase1, public AuxBase2
{
    int base1_func() { cout &lt;&lt; __func__ &lt;&lt; endl; }
    int base2_func() { cout &lt;&lt; __func__ &lt;&lt; endl; }
    
};

int main()
{
    Der *pd = new Der();
    Base1 *p1 = pd;
    Base2 *p2 = pd;
    p1-&gt;func();
    p2-&gt;func();
    pd-&gt;func();

    Der2 *pd2 = new Der2();
    p1 = pd2;
    p2 = pd2;
    p1-&gt;func();
    p2-&gt;func();
}
&lt;/pre&gt;&lt;br /&gt;
Output : &lt;br /&gt;
&lt;pre&gt;der::func
der::func
der::func
base1_func
base2_func
&lt;/pre&gt;</content><link rel='replies' type='application/atom+xml' href='http://the-algo-blog.blogspot.com/feeds/4349976603807268691/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/2282836992153344714/4349976603807268691' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/2282836992153344714/posts/default/4349976603807268691'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/2282836992153344714/posts/default/4349976603807268691'/><link rel='alternate' type='text/html' href='http://the-algo-blog.blogspot.com/2011/07/multiple-inheritance-overriding-same.html' title='Multiple Inheritance : Overriding same named functions in derived.'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-2282836992153344714.post-7118760294941203932</id><published>2011-06-26T05:40:00.000-07:00</published><updated>2011-06-26T05:40:16.486-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="search"/><title type='text'>Finding anagrams, rhyming words and misspelled words in a dictionary.</title><content type='html'>Surprisingly, finding anagrams, rhyming words and corrections (for misspelled words) have a common O(n) solution.&lt;br /&gt;
- To find anagrams, we have a dictionary in which all the words are sorted internally and then compare the input( which is again sorted ). see Bentley (1998) &lt;i&gt;Programming Pearls&lt;/i&gt; Addison-Wesley for further discussion on this.&lt;br /&gt;
&lt;br /&gt;
- To find rhyming words, we have a dictionary in which we have the words in reverse order and we reverse the input and compare for similarity towards the end (say last 3 characters )&lt;br /&gt;
&lt;br /&gt;
- A find the spelling correction, we use a related hybrid approach, to quote Knuth &lt;i&gt;The Art of Computer Programming &lt;/i&gt;Vol.3 (Sorting and Searching) p.394 :&lt;br /&gt;
&lt;tt&gt;&lt;br /&gt;
More complicated search problems can often be reduced to the simpler case &lt;br /&gt;
considered here. For example, suppose that the keys are words that might be &lt;br /&gt;
slightly misspelled; we might want to find the correct record in spite of this &lt;br /&gt;
error. If we make two copies of the file, one in which the keys are in normal &lt;br /&gt;
lexicographic order and another in which they are ordered from right to left (as &lt;br /&gt;
if the words were spelled backwards), a misspelled search argument will probably &lt;br /&gt;
agree up to half or more of its length with an entry in one of these two files. &lt;br /&gt;
&lt;/tt&gt;</content><link rel='replies' type='application/atom+xml' href='http://the-algo-blog.blogspot.com/feeds/7118760294941203932/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/2282836992153344714/7118760294941203932' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/2282836992153344714/posts/default/7118760294941203932'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/2282836992153344714/posts/default/7118760294941203932'/><link rel='alternate' type='text/html' href='http://the-algo-blog.blogspot.com/2011/06/finding-anagrams-rhyming-words-and.html' title='Finding anagrams, rhyming words and misspelled words in a dictionary.'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-2282836992153344714.post-8499563552171545489</id><published>2011-06-26T05:08:00.000-07:00</published><updated>2011-06-26T05:15:55.889-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="search"/><title type='text'>Binary search to find the last and first occurance of an key</title><content type='html'>Given an sorted array with duplicates how do we find the first and last occurance of a Key?&lt;br /&gt;
&lt;br /&gt;
There are three solutions in the code fragment below, all take log(n); the most efficient is from Bentley ( see &lt;i&gt;Programming Pearls&lt;/i&gt; Column 9, a bit trickier to understand )&lt;br /&gt;
&lt;br /&gt;
The obvious way to solve it is to keep saving the last found location. In case of normal binary search, we stop one the key is found. But to find the first occurrence (or the last occurance), instead of stopping, we set the upper bound to mid-1 ( and to find the last occurrence, we set the lower bound to mid+1 ) and continue. When the element is not found, we simply return the last occurrence. Bentley&#39;s method from &lt;i&gt;Programming Pearls&lt;/i&gt; is obviously more efficient, since it eliminates one comparison in the inner loop (however, I found it a bit trickier to understand and implement).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;iframe width=&quot;100%&quot; height=&quot;500&quot; src=&quot;https://docs.google.com/document/pub?id=1Y3u1tnxkPsePKT9qUE3dGyqfk-RbPUIhUfWm948I_lY&amp;amp;embedded=true&quot;&gt;&lt;/iframe&gt;</content><link rel='replies' type='application/atom+xml' href='http://the-algo-blog.blogspot.com/feeds/8499563552171545489/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/2282836992153344714/8499563552171545489' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/2282836992153344714/posts/default/8499563552171545489'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/2282836992153344714/posts/default/8499563552171545489'/><link rel='alternate' type='text/html' href='http://the-algo-blog.blogspot.com/2011/06/binary-search-to-find-last-and-first.html' title='Binary search to find the last and first occurance of an key'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-2282836992153344714.post-3675996086419907498</id><published>2011-06-25T00:11:00.001-07:00</published><updated>2011-06-25T00:11:52.363-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="C++"/><title type='text'>Interesting observation in copy constructor</title><content type='html'>The following code makes an interesting observation w.r.t copy constructors. copy ctor need not be called even when = is used in object definition, a neat optimization by calling the ctor directly..&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#include &lt;iostream&gt;&lt;br /&gt;
using namespace std;&lt;br /&gt;
&lt;br /&gt;
class Foo{&lt;br /&gt;
    public:&lt;br /&gt;
    Foo(const Foo&amp;){ cout &lt;&lt; &quot;in cpy ctor&quot; &lt;&lt; endl; }&lt;br /&gt;
    Foo(int a) { cout &lt;&lt; &quot;in ctro:&quot; &lt;&lt; a &lt;&lt; endl;}&lt;br /&gt;
};&lt;br /&gt;
&lt;br /&gt;
int main()&lt;br /&gt;
{&lt;br /&gt;
    Foo f = 1; // Does this call copy constructor??&lt;br /&gt;
    Foo f2(3);&lt;br /&gt;
    Foo g = f;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
When Executed :&lt;br /&gt;
in ctro:1&lt;br /&gt;
in ctro:3&lt;br /&gt;
in cpy ctor</content><link rel='replies' type='application/atom+xml' href='http://the-algo-blog.blogspot.com/feeds/3675996086419907498/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/2282836992153344714/3675996086419907498' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/2282836992153344714/posts/default/3675996086419907498'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/2282836992153344714/posts/default/3675996086419907498'/><link rel='alternate' type='text/html' href='http://the-algo-blog.blogspot.com/2011/06/interesting-observation-in-copy.html' title='Interesting observation in copy constructor'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-2282836992153344714.post-4267402398768025157</id><published>2011-06-24T00:43:00.000-07:00</published><updated>2011-06-25T07:15:50.932-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="knuth"/><category scheme="http://www.blogger.com/atom/ns#" term="linked lists"/><category scheme="http://www.blogger.com/atom/ns#" term="sorting"/><category scheme="http://www.blogger.com/atom/ns#" term="taocp"/><title type='text'>Sorting linked lists</title><content type='html'>Methods for sorting linked lists :&lt;br /&gt;
* Merge sort ( see Knuth Vol.3 p.164 : Alogrithm L )&lt;br /&gt;
* Radix sort ( see Knuth Vol.3 p.175 )&lt;br /&gt;
&lt;br /&gt;
He also poses the question &lt;tt&gt;&quot;What is the best list-sorting method for six-digit keys, for use on the MIX computer?&quot;(p.309)&lt;/tt&gt; at the end of the Chapter on sorting and gives the following answer:&lt;br /&gt;
&lt;tt&gt;For small N : list insertion, for medium N (say 64) : list merge; for large N, radix list sort. (p.701)&lt;/tt&gt;&lt;br /&gt;
&lt;br /&gt;
Knuth makes an interesting observation:&lt;br /&gt;
&lt;tt&gt;&lt;br /&gt;
An ever-increasing number of &quot;pipeline&quot; or &quot;number-crunching&quot; computers have appeared in recent years. These machines have multiple arithmetic units and look-ahead circuitry so that memory references and computation can be highly overlapped; but their efficiency deteriorates noticeably in the presence of conditional branch instructions unless the branch almost always goes the same way. The inner loop of a radix sort is well adapted to such machines, because it is a straight iterative calculation of typical number-crunching form. Therefore radix sorting is usually more efficient than any other known method for internal sorting on such machines, provided that N is not too small and the keys are not too long. (p.175 Vol.3)&lt;br /&gt;
&lt;/tt&gt;</content><link rel='replies' type='application/atom+xml' href='http://the-algo-blog.blogspot.com/feeds/4267402398768025157/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/2282836992153344714/4267402398768025157' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/2282836992153344714/posts/default/4267402398768025157'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/2282836992153344714/posts/default/4267402398768025157'/><link rel='alternate' type='text/html' href='http://the-algo-blog.blogspot.com/2011/06/sorting-linked-lists.html' title='Sorting linked lists'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-2282836992153344714.post-3667025939187527935</id><published>2011-06-19T03:15:00.000-07:00</published><updated>2011-06-19T08:34:24.662-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="sort"/><title type='text'>Sorting when all the input elements are unknown</title><content type='html'>While reading Knuth&#39;s TAOCP vol.3 Sorting and Searching, p.139, another characteristic of sorting algorithms to me : Few sorting techniques require the entire elements to be present before-hand before sorting, for ex: Selection sort. Other sorting techniques do not need this, for ex: insertion sort (the sort of card-players). To quote Knuth:&lt;br /&gt;
&lt;quote&gt;A selection method requires all of the input items to be present before sorting may proceed, and it generates the final outputs one by one in a sequence. &lt;br /&gt;
&lt;br /&gt;
This is essentially the opposite of insertion, where the inputs are received sequentially but we don not know any of the final outputs until sorting is complete. &lt;br /&gt;
(Knuth(1998) &#39;&#39;TAOCP&#39;&#39;, vol.3 p.139)&lt;br /&gt;
&lt;/quote&gt;</content><link rel='replies' type='application/atom+xml' href='http://the-algo-blog.blogspot.com/feeds/3667025939187527935/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/2282836992153344714/3667025939187527935' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/2282836992153344714/posts/default/3667025939187527935'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/2282836992153344714/posts/default/3667025939187527935'/><link rel='alternate' type='text/html' href='http://the-algo-blog.blogspot.com/2011/06/sorting-when-all-input-elements-are.html' title='Sorting when all the input elements are unknown'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-2282836992153344714.post-1171726369201005026</id><published>2011-06-19T02:46:00.000-07:00</published><updated>2011-06-19T08:39:04.090-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="sort"/><title type='text'>Segregating the positive and negative numbers</title><content type='html'>[Problem from Knuth,TAOCP, vol.3, p.136]&lt;br /&gt;
Design an algorithm that rearranges all the numbers in a given table so that all negative values precede all nonnegative one. (The items need not be sorted completely, just separated between negative and nonnegative.) Your algorithm should use the minimum possible number of exchanges.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Knuth&#39;s solution: &lt;br /&gt;
Knuth suggests a modified radix exchange sort which compares the MSB (bit corresponding to sign )&lt;br /&gt;
&lt;br /&gt;
Another way to do this is to write a specialized comparison routine which is passed to a sorting routine. The routine can be something like:&lt;br /&gt;
&lt;pre&gt;compare(a,b)
  if a&lt;0 and b&lt;0: return 0 // same
  if a&gt;0 and b&gt;0: return 0 // same
  return a&gt;b // one -ve, one +ve
&lt;/pre&gt;&lt;br /&gt;
Other solution is to include counting sort technique.&lt;br /&gt;
The counting sort technique is implemented below in python and is stable.&lt;br /&gt;
&lt;br /&gt;
&lt;pre&gt;import random 

N = 50
# generate an array of +ve and -ve numbers.
array = random.sample( range(-N, N), N )

# counting techinque : 2 pass algorithm
def counting_seperate(array):
    num_pos = 0
    num_neg = 0
    for i in array:
        if i&lt;0: num_neg += 1
        else: num_pos += 1
    # destination array
    dest = [0] * len(array)

    #the final index of a +ve number, can simply be len of array
    num_pos += num_neg

    # Count from n-1 to 0 : stable 
    i = len(array)-1
    while i&gt;=0:
        if array[i]&lt; 0: 
            dest[num_neg-1]=array[i]
            num_neg -= 1 # decrease the index 
        else:
            dest[num_pos-1] = array[i]
            num_pos -= 1 # decrease the index
        i -= 1

    print( &quot;segregated array:&quot;, dest )

if __name__ == &quot;__main__&quot;:
    print( &quot;Original array: &quot;, array )
    counting_seperate(array)

&lt;/pre&gt;</content><link rel='replies' type='application/atom+xml' href='http://the-algo-blog.blogspot.com/feeds/1171726369201005026/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/2282836992153344714/1171726369201005026' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/2282836992153344714/posts/default/1171726369201005026'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/2282836992153344714/posts/default/1171726369201005026'/><link rel='alternate' type='text/html' href='http://the-algo-blog.blogspot.com/2011/06/segregating-positive-and-negative.html' title='Segregating the positive and negative numbers'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-2282836992153344714.post-6403024088159131898</id><published>2011-06-18T23:07:00.000-07:00</published><updated>2011-06-18T23:07:06.998-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="quicksort"/><category scheme="http://www.blogger.com/atom/ns#" term="search"/><category scheme="http://www.blogger.com/atom/ns#" term="sort"/><title type='text'>Finding the mth smallest of a given set on n elements.</title><content type='html'>[Problem posed by C.A.R.Hoare] Suppose that, instead of sorting an entire file, we only want to determine the mth smallest of a given set of n elements. Show that quicksort can be adapted to this purpose avoiding many of the computations required to do a complete sort. ( Knuth(1998)&lt;i&gt;The Art of Computer Programming&lt;/i&gt; Vol.3:Sorting and Searching, p.136 // Bentley (2011) &lt;i&gt;Programming Pearls&lt;/i&gt; Column 11 )&lt;br /&gt;
&lt;pre&gt;In the normal partitioning process of quicksort, if partition position s=m, stop;
if s &lt; m, use the same techinque to find (m-s)th position;
If s &gt; m, find the mth smallest element in the left hand. 
&lt;/pre&gt;</content><link rel='replies' type='application/atom+xml' href='http://the-algo-blog.blogspot.com/feeds/6403024088159131898/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/2282836992153344714/6403024088159131898' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/2282836992153344714/posts/default/6403024088159131898'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/2282836992153344714/posts/default/6403024088159131898'/><link rel='alternate' type='text/html' href='http://the-algo-blog.blogspot.com/2011/06/finding-mth-smallest-of-given-set-on-n.html' title='Finding the mth smallest of a given set on n elements.'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-2282836992153344714.post-6015084896830399262</id><published>2011-06-17T22:25:00.000-07:00</published><updated>2011-06-17T22:25:50.149-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="algorithm"/><category scheme="http://www.blogger.com/atom/ns#" term="search"/><category scheme="http://www.blogger.com/atom/ns#" term="sort"/><title type='text'>Searching a sorted 2D array</title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;&lt;br /&gt;
A 2D Array is sorted on its row and columns, find a key.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;pre&gt;&quot;&quot;&quot;
Program to search an element in a 2-d array
The 2D array has sorted rows and sorted columns
&quot;&quot;&quot;
from random import randrange

N=10 # we will generate a NxN array

# initializes a 2-d array sorted on rows and columns
ARRAY = [ [i for i in range(j,N+j)] for j in range(N) ]

KEY = randrange(0,ARRAY[N-1][N-1])

# We will skip the brute force method of O(n^2) 

# Attempt 1 : Use binary search
def binary_search(lst, l, u, key):
    if l &amp;gt; u : return -1;
    m = (l+u)/2
    if lst[m] == key: return m
    if lst[m] &amp;lt; key: return binary_search(lst, m+1,u, key)
    else : return binary_search(lst, l, m-1,key)


def binsearch_method():
    &quot;Use binary search on each row : takes loglinear time: O( n log(n) )&quot;
    for i in range(N):
        idx = binary_search(ARRAY[i],0,len(ARRAY[i])-1,KEY)
        if idx != -1:
            print(&quot;found %d at %d,%d&quot; % (KEY, i,idx))
            return

def linear_method():
    &quot;search in linear time&quot;
    currow = 0
    curcol = N-1
    steps = 0
    while curcol &amp;gt; 0 and currow &amp;lt; N:
        steps += 1
        #print(currow, curcol)
        # If the elem in a col is greater than key, we can skip the entire col
        if ARRAY[currow][curcol] &amp;gt; KEY: curcol -= 1 
        # If the first element in a row is &amp;gt; than key or if the last elem is &amp;lt; key, we skip the entire row.
        if ARRAY[currow][0] &amp;gt; KEY or ARRAY[currow][curcol] &amp;lt; KEY: currow += 1
        if ARRAY[currow][curcol] == KEY:
            print(&quot;found %d at %d,%d in %d steps&quot; % (KEY, currow,curcol, steps) )
            return

if __name__ == &quot;__main__&quot;:
    print(&quot;Key is %d&quot; % KEY )
    binsearch_method()
    linear_method()


&lt;/pre&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://the-algo-blog.blogspot.com/feeds/6015084896830399262/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/2282836992153344714/6015084896830399262' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/2282836992153344714/posts/default/6015084896830399262'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/2282836992153344714/posts/default/6015084896830399262'/><link rel='alternate' type='text/html' href='http://the-algo-blog.blogspot.com/2011/06/searching-sorted-2d-array.html' title='Searching a sorted 2D array'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-2282836992153344714.post-9020404254495351940</id><published>2011-06-17T09:43:00.000-07:00</published><updated>2011-06-17T22:37:09.644-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="algorithm"/><category scheme="http://www.blogger.com/atom/ns#" term="search"/><title type='text'>The Celebrity Puzzle</title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;Celebrity is a person whom everybody knows but he knows nobody. You have gone to a party. There are total n persons in the party. Your job is to find the celebrity in the party. You can ask questions of the form Does Mr. X know Mr. Y ?. You will get a binary answer for each such question asked. Find the celebrity by asking only O(n) questions. &lt;br /&gt;
&lt;br /&gt;
References : Python Algorithms: Mastering Basic Algorithms in the Python Language pp.85-86  By Magnus Lie Hetland&lt;br /&gt;
&lt;br /&gt;
Solution (in python):&lt;br /&gt;
&lt;pre&gt;####&lt;/pre&gt;&lt;pre&gt;from random import randrange
# Number of persons
N = 100
# the graph of connections built using random values.
G = [ [randrange(2) for i in range(N)] for i in range(N) ]

def create_celebrity():
    C = randrange(N)
    # ensure that we have celebrity at C
    for i in range(N):
        G[i][C] = 1
        G[C][i] = 0
    print(&quot;rand celeb : %d&quot; % C)


def bruteforce():
    &quot;&quot;&quot;Brute force solution to the celebrity problem&quot;&quot;&quot;
    n = len(G)
    steps = 0
    for i in range(N):
        is_celeb = 1
        for j in range(N):
            steps += 1
            if i == j: continue
            # i knows j and is not a celebrity
            # j does not know i, break
            if G[i][j] or not G[j][i]: 
                is_celeb = 0;
                break 
        if is_celeb:
            print(&quot;found celeb at %d in %d steps&quot; % (i, steps) )
            return i

def bruteforce_improved():
    &quot;&quot;&quot;Improvement to brute force&quot;&quot;&quot;
    # At every-step we can eliminate either i or j
    u,v = 0,1
    steps = 0
    while u &amp;lt; N and v &amp;lt; N:
        steps += 1
        if u == v: v = u+1
        # if u knows v, then u is not a celeb, 
        # if u does not know v, then v is not a celeb
        if G[u][v]: u = u+1
        else : v = v+1
    print(&quot;found celeb at %d in %d steps&quot; % (u, steps) )

def linear_time():
    &quot;&quot;&quot; finds in linear time : see : 
        Python Algorithms: Mastering Basic Algorithms in the Python Language p.86
        By Magnus Lie Hetland
    &quot;&quot;&quot;
    u,v = 0,1 # the first two persons
    steps = 0
    # c corresponds to the third to the last person...
    for c in range(2, N):
        steps += 1
        if G[u][v]: u=c # u knows v, replace u
        else:       v=c # otherwise, u is a candidate

    if v==c : c=u #if v has reached end of list, use u.
    else:     c=v

    for i in range(N):
        if c==i: continue
        if G[c][i]:break
        if not G[i][c]: break
    else:
        print(&quot;found celeb at %d in %d steps&quot; % (c, steps) )



if __name__ == &#39;__main__&#39;:
    create_celebrity()
    bruteforce()
    bruteforce_improved()
    linear_time()

&lt;/pre&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://the-algo-blog.blogspot.com/feeds/9020404254495351940/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/2282836992153344714/9020404254495351940' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/2282836992153344714/posts/default/9020404254495351940'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/2282836992153344714/posts/default/9020404254495351940'/><link rel='alternate' type='text/html' href='http://the-algo-blog.blogspot.com/2011/06/celebrity-puzzle.html' title='The Celebrity Puzzle'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-2282836992153344714.post-1341716875528366205</id><published>2011-05-08T05:10:00.000-07:00</published><updated>2011-05-08T05:10:48.080-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="array"/><category scheme="http://www.blogger.com/atom/ns#" term="maxmin"/><title type='text'>Maximum subarray problem</title><content type='html'>Given a array with -ve and +ve integers, find the sub-array with maximum sum.&lt;br /&gt;
&lt;br /&gt;
Answer :&lt;br /&gt;
See John Bentley (1986) &lt;i&gt;&lt;a href=&quot;http://books.google.co.in/books?id=kse_7qbWbjsC&amp;lpg=PA218&amp;dq=maximum%20subarray%20problem&amp;pg=PA77#v=onepage&amp;q&amp;f=false&quot;&gt;Programming Perls&lt;/a&gt;&lt;/i&gt; Addison Wesley for discussion of various implementations, ranging from brute force, O(n^3), solution which remembers previous sums O(n^2), divide and conquer O(n log(n)) and the linear approach. The book can be downloaded &lt;a href=&quot;http://www.it.iitb.ac.in/~deepak/deepak/placement/Programming_pearls.pdf&quot;&gt;here&lt;/a&gt;&lt;br /&gt;
&lt;br /&gt;
See also : V.V. Muniswamy in &lt;a href=&quot;http://books.google.co.in/books?id=6eIPgTo8AaIC&amp;lpg=PA117&amp;dq=maximum%20subarray%20problem&amp;pg=PA117#v=onepage&amp;q=maximum%20subarray%20problem&amp;f=false&quot;&gt;&lt;i&gt;Design And Analysis Of Algorithms&lt;/i&gt;&lt;/a&gt;&lt;br /&gt;
&lt;br /&gt;
The below code in python uses the technique described in Muniswamy and Bentley above, using dynamic programming and runs in linear time:&lt;br /&gt;
&lt;pre&gt;a = [31, -41, 59, 26, -53, 58, 97, -93, -23, 84]


def linear_method2():
    maxsofar = 0
    maxhere = 0
    for i in range(0, len(a)):
        maxhere = max(maxhere + a[i], 0)
        maxsofar = max(maxsofar, maxhere)
        print( a[:i+1])
        print( &#39;maxhere %d maxsofar %d &#39; % (maxhere, maxsofar) )
    print( maxsofar)

def linear_method1():
    # [a] [b] [c] [d]  [e]  [f] [g] ...
    #      |   |   |    |
    #      L   U  i-1   i           
    L = 0 # lowerbound of the max subarray
    U = 0 # upperbound of the max subarray
    summax = 0 # the current max subarray sum, i.e sum(a[L:U])
    sumcur = 0 # the current sum from L to i-1

    for i in range(0, len(a) ):
        # If introducing the next element increases the maximum sum,
        # then include the element
        if (a[i]+sumcur) &gt; summax and sumcur&gt;0 :
            print( &#39; (a[i]+sumcur) &gt; summax &#39;)
            U = i
            sumcur += a[i]
            summax = sumcur
        # If the current element cannot be introduced above ( since there are -ve in b/w ),
        # but current element is greater than max sum so far =&gt; start from this point
        elif a[i] &gt; summax:
            print( &#39;a[i] &gt; summax&#39; )
            L=i
            U=i
            summax = sumcur = a[i]
        # increase the current sum
        else:
            sumcur += a[i]
        print( &#39;sumcur %d summax %d L %d U %d Array %s&#39; % (sumcur, summax, L, U, a[L:U+1]) )
    print(&#39;maxsubarray : %s&#39; % a[L:U+1])
    print(&#39;sum : %d&#39; % summax)
    
linear_method2()
print(&#39;------------&#39;)
linear_method1()

&lt;/pre&gt;&lt;br /&gt;
See also : http://en.wikipedia.org/wiki/Maximum_subarray_problem</content><link rel='replies' type='application/atom+xml' href='http://the-algo-blog.blogspot.com/feeds/1341716875528366205/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/2282836992153344714/1341716875528366205' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/2282836992153344714/posts/default/1341716875528366205'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/2282836992153344714/posts/default/1341716875528366205'/><link rel='alternate' type='text/html' href='http://the-algo-blog.blogspot.com/2011/05/maximum-subarray-problem.html' title='Maximum subarray problem'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-2282836992153344714.post-8911723048237313315</id><published>2009-11-08T06:59:00.000-08:00</published><updated>2009-11-08T07:03:14.640-08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="unix"/><title type='text'>Properties inherited during fork()</title><content type='html'>What are the properties inherited by a child process during fork()?&lt;br /&gt;Answer:&lt;br /&gt;&lt;font color=&quot;#eeeeec&quot;&gt;&lt;br /&gt;Properties inherited:&lt;br /&gt;* open file descriptors&lt;br /&gt;* real uid, real gid, effective uid, effective group id&lt;br /&gt;* process gid&lt;br /&gt;* controlling terminal&lt;br /&gt;* set-user-ID flag and set-group-ID flag&lt;br /&gt;* current working directory&lt;br /&gt;* root dir&lt;br /&gt;* file mode creation mask&lt;br /&gt;* signal mask&lt;br /&gt;* Environment&lt;br /&gt;&lt;br /&gt;Differences:&lt;br /&gt;* alarms.&lt;br /&gt;* pending signals.&lt;br /&gt;&lt;br /&gt;( selected from Steven Richards, p.192 )&lt;br /&gt;&lt;/font&gt;</content><link rel='replies' type='application/atom+xml' href='http://the-algo-blog.blogspot.com/feeds/8911723048237313315/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/2282836992153344714/8911723048237313315' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/2282836992153344714/posts/default/8911723048237313315'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/2282836992153344714/posts/default/8911723048237313315'/><link rel='alternate' type='text/html' href='http://the-algo-blog.blogspot.com/2009/11/properties-inherited-during-fork.html' title='Properties inherited during fork()'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-2282836992153344714.post-367758470016548926</id><published>2009-11-08T06:47:00.000-08:00</published><updated>2009-11-08T06:57:21.539-08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="memory"/><category scheme="http://www.blogger.com/atom/ns#" term="unix"/><title type='text'>Memory Layout of a Program in UNIX</title><content type='html'>Memory layout of a Program in a UNIX-environment:&lt;br /&gt;&lt;br /&gt;&lt;font color=&quot;#eeeeec&quot;&gt;&lt;br /&gt;&lt;br /&gt;Reference : &quot;The Environment of a Unix Process&quot; in &lt;span style=&quot;font-style:italic;&quot;&gt;Advanced Programming in the UNIX Environment&lt;/span&gt; Richard Stevens, p.168&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;(High address)&lt;br /&gt;+-------------------+&lt;br /&gt;|                   |  cmd line args and env vars&lt;br /&gt;|                   |&lt;br /&gt;+-------------------+&lt;br /&gt;|    stack          | &lt;br /&gt;+-------------------+&lt;br /&gt;|       ↓           |&lt;br /&gt;|                   |&lt;br /&gt;|       ↑           |&lt;br /&gt;+-------------------+&lt;br /&gt;|    heap           | &lt;br /&gt;+-------------------+&lt;br /&gt;|Uninitialized data | init to zero by exec&lt;br /&gt;|   (bss)           |&lt;br /&gt;+-------------------+  _&lt;br /&gt;| initialized data  |   |&lt;br /&gt;+-------------------+   |--read from program file by exec&lt;br /&gt;|    text           |   |&lt;br /&gt;+-------------------+  _|&lt;br /&gt;(Low address)&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;/font&gt;</content><link rel='replies' type='application/atom+xml' href='http://the-algo-blog.blogspot.com/feeds/367758470016548926/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/2282836992153344714/367758470016548926' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/2282836992153344714/posts/default/367758470016548926'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/2282836992153344714/posts/default/367758470016548926'/><link rel='alternate' type='text/html' href='http://the-algo-blog.blogspot.com/2009/11/memory-layout-of-c-program.html' title='Memory Layout of a Program in UNIX'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry></feed>