$(document).ready(function() { $('pre code').each(function(i, block) { hljs.highlightBlock(block); }); });

Monday, January 3, 2011

excellent NON-RECURSIVE algorithm for QUICK SORT

 /*------This algo is NON-RECURSIVE algo for QUICK SORT (as required in UPTU exams)------
 

The variables used are described as follows:
item- item part of node
next- next pointer address part of the node
a- pointer to the node to be sorted
FP- Node pointer to hold forward position of nodes
BP- Node pointer to hold backward position of nodes

Integer variables:
i- used in 'for' loops
Temp- temporary variable
Up- Used to hold INTEGER location of backward pointer
Down- Used to hold INTEGER location of Forward pointer
iUp- To save Up value for future use
iDown- To save Down value for future use
C- acts as counter
*/

 
QuickSort[a,FP,BP,t]
{
1. initialize i,Temp,loc,Up,Down,iUp,iDown,C,count;


2. set STACK[TOP]=NULL;

 
3. if(count==0)
  PUSH(LAST);
  PUSH(1);// 0 will be on top

 
4. Repeat while(STACK[TOP]!=NULL)
  (a).set Down=STACK[TOP],loc=Down,iDown=Down, and POP();

  (b).set Up=STACK[TOP],iUp=Up,and POP();

  (c). set a=START and Repeat for i=1,2,3,...,loc
        a=a->next, and i=i+1

  (d). set FP=START and Repeat for i=1,2,3,...,Down
        FP=FP->next, and i=i+1

  (e). set BP=START and Repeat for i=1,2,3,...,Up
        BP=BP->next, and i=i+1

  (f). Repeat until up>down
       (i).Reapeat for C=iDown,...,iUp, AND FP->item <= a->item
           FP=FP->next, and Down=Down+1;
      (ii).Repeat for C=iUp,....iDown AND BP->item > a->item
           set Up=Up-1, and BP=START;
           Repeat for i=1,2,..,Up.
           BP=BP->next;
     (iii).If(Up&gt>Down)
           Temp=BP->item;
           BP->item=FP->item;
           FP->item=Temp;

 
  (g).Set Temp=a->item;
            a->item=BP->item;
            BP->item=Temp;

  (h).if(Up-loc >= 2 && Up-1>=1)
       PUSH(Up-1);//up
       PUSH(loc);//down   //Partition1 of list
  (i).if(iUp-Up >= 2)
      PUSH(iUp);//Up
      PUSH(Up+1);//down  //Partition 2
5.exit.

//
Step 'a' and 'b' assigns the value on STACK[top] to 'up' and 'down' pointers.
Step 'c' takes the pointer 'a' to the location, of the pointer in the complete list, which needs to be sorted
Step 'd' takes the Forward pointer upto the 'down' location
Step 'e' takes the Backward pointer upto the 'up' location
Step 'f' performs quick sort mechanism on the partition and moves the pointers forward and backward
as required.
Step 'g' swaps the value at location 'up' with the value at location 'a', that is, the value which was to be sorted
Step 'h' and 'i' makes partition if there are more than 1 element to be sorted in the list.

No comments:

Post a Comment

Contact Me

Name

Email *

Message *