Pages

Monday, September 1, 2014

Quick Sort

Algorithm

The divide-and-conquer strategy is used in quicksort. Below the recursion step is described:
  1. Choose a pivot value. We take the value of the middle element as pivot value, but it can be any value, which is in range of sorted values, even if it doesn't present in the array.
  2. Partition. Rearrange elements in such a way, that all elements which are lesser than the pivot go to the left part of the array and all elements greater than the pivot, go to the right part of the array. Values equal to the pivot can stay in any part of the array. Notice, that array may be divided in non-equal parts.
  3. Sort both parts. Apply quicksort algorithm recursively to the left and the right parts.
PDF

C++

void quickSort(int arr[], int left, int right) {
      int i = left, j = right;
      int tmp;
      int pivot = arr[(left + right) / 2];

      /* partition */
      while (i <= j) {
            while (arr[i] < pivot)
                  i++;
            while (arr[j] > pivot)
                  j--;
            if (i <= j) {
                  tmp = arr[i];
                  arr[i] = arr[j];
                  arr[j] = tmp;
                  i++;
                  j--;
            }
      };

      /* recursion */
      if (left < j)
            quickSort(arr, left, j);
      if (i < right)
            quickSort(arr, i, right);
}




PSEUDO CODE:


Quicksort (int data[],int left,int right) {
   int mid,tmp,i,j;
   

   i = left;
   j = right;
   mid = data[(left + right)/2];
   do {
        while(data[i] < mid)
           i++;
       while(mid < data[j])
           j--;
       if (i <= j) {
           tmp = data[i];
           data[i] = data[j];
           data[j] = tmp;
           i++;
           j--;
       }
   } while (i <= j);
   if (left < j) Quicksort(data,left,j);
   if (i < right) Quicksort(data,i,right);
}











 

Tuesday, August 19, 2014

Find area of circle and square using Pure Virtual Function

#include <iostream.h>
#include<conio.h>

class Shape                    /* Abstract class */
{
    protected:
       float l;
    public:
       void get_data()          /* Note: this function is not virtual. */
       {
  cin>>l;
       }

       virtual float area() = 0; /* Pure virtual function */
};

class Square : public Shape
{
    public:
       float area()
       {   return l*l;  }
};

class Circle : public Shape
{
    public:
       float area()
       { return 3.14*l*l; }
};

void main()
{
    Square s;
    Circle c;
    cout<<"Enter length to calculate area of a square: ";
    s.get_data();
    cout<<"Area of square: "<<s.area();
    cout<<"\nEnter radius to calcuate area of a circle:";
    c.get_data();
    cout<<"Area of circle: "<<c.area();

    getch();
}