Thursday, December 29, 2011

Array [XI] [Queue, Circular Queue, Priority Queue]



Queue 

A queue refers to lining up jobs for a computer or device. For example, if you want to print a number of documents, the operating system or spooler queues the documents by placing them in a special area called a print buffer or print queue. The printer then pulls the documents off the queue one at a time. Another term for this is print spooling. This is often referred to as FIFO (first in, first out).

The order in which a system executes jobs on a queue depends on the priority system being used. Most commonly, jobs are executed in the same order that they were placed on the queue, but in some schemes certain jobs are given higher priority is know as priority queue. Queues are common in computer programs, where they are implemented as data structures coupled with access routines, as an abstract data structure or in object-oriented languages as classes. Common implementations are circular buffers and linked lists.

Algorithm

Addition into a queue
procedure Push (var Elem)
  {
      add item to the queue q
  }
begin
  if rear=n
      then
           display queue full
  else
      begin
           rear :=rear+1;
           q[rear]:=Elem;
      end
end (of Push)

Deletion in a queue
procedure POP ()
  begin
      if front = rear
           then
              display queue empty
      else
           begin
              front := front+1
              item := q[front];
           end
  end (of Pop}

Source Code

#include <stdio.h>
#include <conio.h>
#define MAX 5
  int front,rear;
  int qu[MAX];
  void push()
      {
           if(rear>=MAX)
              {
                   printf("\n\tQueue is full\n");
              }
           else
              {
                   printf("\n\tEnter an Element : ");
                   scanf("%d",&qu[rear]);
                   rear++;
              }
      }

  void pop()
      {
           if(front==rear)
              {
                   printf("\n\tQueue is empty ");
              }
           else
              {
                   printf("\n\tNumber popped =  %d",qu[front]);
                   front++;
              }
      }

  void disp()
      {
           int i;
           if(front==rear)
              {
                   printf("\n\tQueue is empty ");
              }
           else
              {
                   printf("\n\tQueue List ..");
                   for(i=front;i<rear;i++)
                        {
                            printf("%d  ",qu[i]);
                        }
              }
      }

  void main()
      {
           int ch,num;
           rear=front=0;
           clrscr();
           front=rear=0;
           while(ch!=4)
              {
                   printf("\n\t ---- Queue Menu ----\n");
                   printf("\n\t1.Push\n\t2.Pop\n\t3.Display\n\t4.Exit");
                   printf("\n\t\tEnter a Choice : ");
                   scanf("%d",&ch);
                   switch(ch)
                        {
                            case 1: push();break;
                            case 2: pop();break;
                            case 3: disp();break;
                            case 4: printf("\n\t\tQuit......");
                                                getch();
                                                exit(0);
                            default :printf("\n\tInvalid Choice ..\n");
                        }
              }
           getch();
      }

Circular Queue

In case of a ordinary queue, the insertion take place from the front end and the deletion take place  from the rear end and the space of the queue is not utilized for the further storage. Circular Queue can effectively utilise the memory space. If we have a normal queue and have deleted some elements from there then empty space is created there and even if the queue has empty cells then also we cannot insert any new element because the insertion has to be done from one side only. But in case of circular queue the front and rear are adjacent to each other.

Source Code


#include <stdio.h>
#include <conio.h>

int Cqueue[MAX];
int front,int rear;
  //Push Function
  void Push()
      {
           if((front == 0 && rear == MAX-1) || (front == rear+1))
              {
                   printf("\n\tQueue is Full\n");
                   return;
              }
           if(front==-1)
              {
                   front=rear=0;
              }

           else if(rear == MAX-1)
              {
                   rear = 0;
              }
           else
              {
                   rear = rear+1;
              }
           printf("\n\tEnter the Element : ");
           scanf("%d", &Cqueue[rear]);
      }

  //Pop Function
  void Pop()
      {
           if (front < 0)
              {
                   printf("\n\tQueue is Empty\n");
                   return;
              }
           printf("\n\tElement Popped from the Queue  : %d\n",Cqueue[front]);
           if(front == rear)
              {
                   front=-1;
                   rear =-1;
              }
           else if(front == MAX-1)
              {
                   front = 0;
              }
           else
              {
                   front = front+1;
              }
      }
 
//Print the Queue
  void disp()
      {
           int frnt = front;
           if(front <0 )
              {
                   printf("\n\tQueue is empty\n");
                   return;
              }
           printf("Elements in the Queue : ");
           if( frnt <= rear )
              {
                   for(frnt=front;frnt<=rear;frnt++)
                        {
                            printf("%d ",Cqueue[frnt]);
                        }
              }
           else
              {
                   for(frnt=front;frnt<MAX;frnt++)
                        {
                            printf("%d ",Cqueue[frnt]);
                        }
                   for(frnt=0;frnt<= rear;frnt++)
                        {
                            printf("%d ",Cqueue[frnt]);
                        }
           }
       printf("\n");
      }

  //Main Function
  void main()
      {
           int ch=0;
           clrscr();
           rear=front=-1;
           while(ch!=4)
              {
                   printf("\n\t1.Push\n\t2.Pop\n\t3.Display\n\t4.Quit");
                   printf("\n\tEnter a choice : ");
                   scanf("%d",&ch);
                   switch(ch)
                        {
                            case 1 :Push();break;
                            case 2 :Pop();break;
                            case 3: disp();break;
                           case 4: printf("\n\t..Quit...");getch();exit(0);
                            default:printf("\n\t* Invalid Option *\n");
                        }
              }
           getch();
      }

Priority Queue

a priority queue is an abstract data type which is like a regular queue or stack data structure, but additionally, each element is associated with a "priority". The node with highest priority will be popped first. Priority queuing can be used to manage limited resources such as bandwidth on a transmission line from a network router.

Source Code

#include <stdio.h>
#include <conio.h>
#include <stdlib.h>

#define MAX 5
int rear,front,qu[MAX],priority[MAX];

  void add()
      {
           int i,j,t,t1;
           if(rear>=MAX)
              {
                   printf("\n\tQueue is full. ");
                   return;
              }
           printf("\n\n\n\n\tEnter job name : ");
           scanf("%d",&qu[rear]);
           printf("\n\tEnter job priority : ");
           scanf("%d",&priority[rear]);
           rear++;
           for(i=front;i<rear;i++)
              {
                   for(j=front;j<rear-front-1;j++)
                        {
                            if(priority[j]>priority[j+1])
                                 {
                                      t=priority[j];
                                      t1=qu[j];
                                      priority[j]=priority[j+1];
                                      priority[j+1]=t;
                                      qu[j]=qu[j+1];
                                      qu[j+1]=t1;
                                }
                        }
              }
      }

  void display()
      {
           int i;
           if(front==rear)
              {
                   printf("\n\n\t***Queue is Empty***");
                   return;
              }
           printf("\n\t --- Queue on Priority ---");
           printf("\n\t---------------------------- ");
           for(i=front;i<rear;i++)
              {
                   printf("\n\t\t %d\t %d",qu[i],priority[i]);
              }
      }

  void del()
      {
           if(front==rear)
              {
                   printf("\n\n\t\t***Underflow***");
                   return;
              }
           printf("\n\n\tElement Popped =  %d.",qu[front]);
           front++;
      }

  void main()
      {
           int ch;
           rear=front=0;
           clrscr();
           printf("\n\t*Queue Menu*\n");
           do
              {
                   printf("\n\n\t1. Push.\n\t2. Pop.\n\t3. Display\n\t4. Exit");
                   printf("\n\tEnter a choice : ");
                   scanf("%d",&ch);
                   switch(ch)
                        {
                            case 1: add();break;
                            case 2: del();break;
                            case 3: display();break;
                            case 4: printf("\n\t\t.....Quit.....");
                                                getch();
                                                exit(0);
                            default:         printf("\n\t**Invalid Choice **");
                        }
              }while(1);
           getch();
      }

Thursday, December 22, 2011

Array [X] [ Shell Sort and Bucket Sort ]



Shell Sort –  Shellsort, also known as Shell sort or Shell's method is an in-place comparison sort. It generalizes an exchanging sort, such as insertion or bubble  sort, by allowing the comparison and exchange of elements that lie far apart. Its first version was published by Donald Shell. The running time of Shellsort is heavily dependent on the gap sequence it uses. For many practical variants, determining their time complexity remains an open problem.

Complexity :

Worst case performance              O(n^2)
Best case performance                O(N)
Average case performance           depends on gap sequence

Algorithm.

function shellsort(int arr[],int n)
           int last,tmp,limit,temp,k
           int mid=n/2
           while mid>0
              do
                   last=0;
                   limit=n-mid;
                   while last==0
                        do
                            tmp=0;
                            for k=0 to limit-1 step 1
                                do
                                      if arr[k]>arr[k+mid]
                                                then
                                                          temp=arr[k]
                                                          arr[k]=arr[k+mid]
                                                          arr[k+mid]=temp
                                                          tmp=k
                                                endif
                                endfor
                            limit=tmp-mid
                            if tmp==0 then
                                then
                                      last=1
                                endif
                        enddo
                   mid=mid/2
              enddo
      end


Source Code


#include <stdio.h>
#include <conio.h>

//Shell Sort
void shellsort(int arr[],int n)
      {
           int last,tmp,limit,temp,k;
           int mid=n/2;
           while(mid>0)
              {
                   last=0;
                   limit=n-mid;
                   while(last==0)
                        {
                            tmp=0;
                            for(k=0;k<limit;k++)
                                {
                                      if(arr[k]>arr[k+mid])
                                                {
                                                          temp=arr[k];
                                                         arr[k]=arr[k+mid];
                                                          arr[k+mid]=temp;
                                                          tmp=k;
                                                }
                                }
                            limit=tmp-mid;
                            if(tmp==0)
                                {
                                      last=1;
                                }
                        }
                   mid=mid/2;
              }
      }

//Main Funtion
  void main()
      {
           int i;
           int Arr[20],n;
           clrscr();
           printf("\n\tEnter Size of Array below 20 : ");
           scanf("%d",&n);
           for(i=0;i<n;i++)
              {
                   printf("\n\tEnter Array Element at [%d] : ",i);
                   scanf("%d",&Arr[i]);
              }
           printf("\n\tOriginal Array :  ");
           for(i=0;i<n;i++)
              {
                   printf("%d ",Arr[i]);
              }
           shellsort(Arr,n);
           printf("\n\tAfter Sort :  ");
           for(i=0;i<n;i++)
              {
                   printf("%d ",Arr[i]);
              }
           getch();
      }

Bucket Sort – Bucket sort is a divide and conquer sorting algorithm that generalizes Counting sort by partitioning an array into a finite number of buckets. Each bucket is then sorted individually, either using a different sorting algorithm, or by recursively applying the bucket sorting algorithm. A variation of this method called the single buffered count sort is faster than quicksort.[citation needed] Due to the fact that bucket sort must use a limited number of buckets it is best suited to be used on data sets of a limited scope. Bucket sort would be unsuitable for data such as social security numbers - which have a lot of variation.

Bucket sort works as follows:

1.     Set up an array of initially empty "buckets."
2.     Scatter: Go over the original array, putting each object in its bucket.
3.     Sort each non-empty bucket.
4.     Gather: Visit the buckets in order and put all elements back into the original array.

Complexity :

         Worst case performance             O(n2)
         Average case performance          O(n + k)
         Worst case space complexity       O(n * k)


Algorithm.

function BucktSort(int A[], int n)
           int bucks[10][MAX]={{0}},f=0,i,j,m,k
           i=1
           while(f!=n)
              do
                   f=0;
                   for j=1 to n-1
                        do
                            bucks[(A[j]/i)%10][j] = A[j]
                            if  (A[j]/i)%10  == 0  then
                                then
                                      f++
                                endif
                        endfor
                   if f == n
                        then
                            print “Sorted Values "
                            for j=0  to n-1
                                do
                                      print A[j]
                                enddo
                        endif
                   m=0
                   for j=0 to 9
                        do
                            fork=0 to n-1
                                {
                                      if bucks[j][k] > 0
                                                then
                                                          A[m] = bucks[j][k]
                                                          bucks[j][k] = 0
                                                         m++
                                                endif
                                endfor
                        endfor
                   i=i*10
              enddo
      end

Source Code


#include <stdio.h>
#include <conio.h>
#define MAX  20
   void BucktSort(int A[], int n)
      {
           int bucks[10][MAX]={{0}},f=0,i,j,m,k;
           for(i=1;f!=n;i*=10)
              {
                   f=0;
                   for(j=0;j<n;j++)
                        {
                            bucks[(A[j]/i)%10][j] = A[j];
                            if ( (A[j]/i)%10  == 0 )
                                {
                                      f++;
                                }
                        }
                   if (f == n)
                        {
                            printf("\nSorted Values ");
                            for(j=0 ;  j < n ; j++)
                                {
                                      printf("%d " , A[j]);
                                }
                        }
                   for(j=0,m=0;j<10;j++)
                        {
                            for(k=0;k<n;k++)
                                {
                                      if( bucks[j][k] > 0 )
                                                {
                                                          A[m] = bucks[j][k];
                                                          bucks[j][k] = 0 ;
                                                          m++;
                                                }
                                }
                        }

              }
    }

  //Main Function
  void main()
      {
           int A[MAX] ;
           int   i, n ;
           clrscr();
           printf("\nEnter Size of Array [Below 20] : ");
           scanf("%d",&n);
           for(i=0 ;  i < n ; i++)
              {
                   scanf("%d",&A[i]);
              }
           printf("\nOrigianl Values : ");
           for(i=0 ;  i < n ; i++)
              {
                   printf("%d ", A[i]);
              }
           BucktSort(A,n);
           getch();
      }