Search here

Pages

Saturday, August 13, 2011

Binary Search

In computer science, a binary search or half-interval search algorithm finds the position of a specified value (the input "key") within a sorted array. At each stage, the algorithm compares the input key value with the key value of the middle element of the array. If the keys match, then a matching element has been found so its index, or position, is returned. Otherwise, if the sought key is less than the middle element's key, then the algorithm repeats its action on the sub-array to the left of the middle element or, if the input key is greater, on the sub-array to the right. If the remaining array to be searched is reduced to zero, then the key cannot be found in the array and a special "Not found" indication is returned.
          A binary search halves the number of items to check with each iteration, so locating the an item (or determining its absence) takes logarithmic time. A binary search is a dichotomic divide and conquer search algorithm.
           Searching a sorted collection is a common task. A dictionary is a sorted list of word definitions. Given a word, one can find its definition. A telephone book is a sorted list of people's names, addresses, and telephone numbers. Knowing someone's name allows one to quickly find their telephone number and address.
If the list to be searched contains more than a few items (a dozen, say) a binary search will require far fewer comparisons than a linear search, but it imposes the requirement that the list be sorted. Similarly, a hash search can be faster than a binary search but imposes still greater requirements. If the contents of the array are modified between searches, maintaining these requirements may take more time than the searches! And if it is known that some items will be searched for much more often than others, and it can be arranged that these items are at the start of the list, then a linear search may be the best.
Program for Binary Search 
#include<stdio.h>
#include<iostream.h>
#include<iomanip.h>
#include<conio.h>
int bsearch(int a[],int low,int high,int ele);
void main()
{
int a[10],i,n,ele,found=0;
clrscr();
cout<<"enter the no of elements in to array";
cin>>n;
cout<<"enter elements in sorted order";
for (i=0;i<n;i++)
{
cin>>a[i];
}
cout<<"enter the element to be searched";
cin>>ele;
cout.setf(ios::fixed|ios::left);
cout<<setw(10)<<"LOW"<<setw(10)<<"MID"<<setw(10)<<"HIGH";
cout<<endl;
found=bsearch(a,0,n-1,ele);
if(found==-1)
cout<<"element not found";
else
cout<<"element found at location "<<found;
getch();
}
int bsearch(int a[],int low, int high, int ele)
{
if(low<=high)
{
int mid =(low+high)/2;
cout<<setw(10)<<low;
cout<<setw(10)<<mid;
cout<<setw(10)<<high;
cout<<endl;
if(ele==a[mid])
return mid;
else if(ele<a[mid])
high=mid-1;
else if(ele>a[mid])
low=mid+1;
bsearch(a,low,high,ele);
}
else
return -1;
}

Read Full

Linear Search

In computer science, linear search or sequential search is a method for finding a particular value in a list, that consists of checking every one of its elements, one at a time and in sequence, until the desired one is found.
           Linear search is the simplest search algorithm; it is a special case of brute-force search. Its worst case cost is proportional to the number of elements in the list; and so is its expected cost, if all list elements are equally likely to be searched for. Therefore, if the list has more than a few elements, other methods (such as binary search or hashing) will be faster, but they also impose additional requirements.
For a list with n items, the best case is when the value is equal to the first element of the list, in which case only one comparison is needed. The worst case is when the value is not in the list (or occurs only once at the end of the list), in which case n comparisons are needed.
If the value being sought occurs k times in the list, and all orderings of the list are equally likely, the expected number of comparisons is
\begin{cases} 
  n                   & \mbox{if } k = 0 \\[5pt]
  \displaystyle\frac{n + 1}{k + 1} & \mbox{if } 1 \le k \le n.
\end{cases}
For example, if the value being sought occurs once in the list, and all orderings of the list are equally likely, the expected number of comparisons is \frac{n + 1}2. However, if it is known that it occurs once, then at most n - 1 comparisons are needed, and the expected number of comparisons is
\displaystyle\frac{(n + 2)(n-1)}{2n}
(for example, for n = 2 this is 1, corresponding to a single if-then-else construct).
Either way, asymptotically the worst-case cost and the expected cost of linear search are both O(n).

Non-uniform probabilities

The performance of linear search improves if the desired value is more likely to be near the beginning of the list than to its end. Therefore, if some values are much more likely to be searched than others, it is desirable to place them at the beginning of the list.
In particular, when the list items are arranged in order of decreasing probability, and these probabilities are geometrically distributed, the cost of linear search is only O(1). If the table size n is large enough, linear search will be faster than binary search, whose cost is O(log n).
Program for linear search 
#include<stdio.h>
#include<iostream.h>
#include<iomanip.h>
#include<conio.h>
int lsearch(int a[],int,int);
void main()
{
int a[10],i,n,ele,found=0;
clrscr();
cout<<"enter the no of elements in to array";
cin>>n;
cout<<"enter elements ";
for (i=0;i<n;i++)
{
cin>>a[i];
}
cout<<"enter the element to be searched";
cin>>ele;
found=lsearch(a,ele,n);
if(found==-1)
cout<<"element not found";
else
cout<<"element found at location "<<found;
getch();
}
int lsearch(int a[],int ele,int n)
{
int i,c=0;
for(i=0;i<n;i++)
{
if(a[i]==ele)
{
return i;
c++;
}
}
if(c==0)
return -1;
}


Read Full

Fibonacci Series printing using Functions

#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
void fibonacci(int );
void main()
{
int n;
clrscr();
cout<<"Enter a digit to findout fibonacci around it's range";
cin>>n;
fibonacci(n);
getch();
}
void fibonacci(int x)
{
int a=0,b=1,c;
cout<<a<<"\t"<<b;
while(c<x)
{
c=a+b;
a=b;
b=c;
cout<<"\t"<<c;
}
}
 
Read Full

Factorial Using Recursion

Proram for Factorial using recursion 
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
long int factorial(int );
void main()
{
long int f;
int n;
cout<<"Enter a digit to findout it's factorial";
cin>>n;
f=factorial(n);
cout<<"Factorial is"<<f;
getch();
}
long int factorial(int x)
{
while(x>=0)
{
if(x==0)
return 1;
else
{
int n=x*factorial(x-1);
return n;
}
}
}
Read Full

Pass by Value(swapping)

Program for Passby Value-PARAMETER PASSING 
#include<iostream.h>
#include<conio.h>
void swap(int,int);
void main()
{
int a,b;
cout<<"Enter any two numbers";
cin>>a>>b;
swap(a,b);
cout<<"\n the swapped valuesin the main funtion are"<<a<<"and"<<b;
getche();
}
void swap(int x,int y)
{
int t;
t=x;
x=y;
y=t;
cout<<"\n the  swapped values in the function are"<<x<<"and"<<y;

}
Read Full

Pass by Address(swapping)

Program for Passby Address-PARAMETER PASSING 
#include<iostream.h>
#include<conio.h>
void swap(int &,int &);
void main()
{
int a,b;
cout<<"Enter any two numbers";
cin>>a>>b;
swap(a,b);
cout<<"\n the swapped valuesin the main funtion are"<<a<<"and"<<b;
getche();
}
void swap(int &x,int &y)
{
int t;
t=x;
x=y;
y=t;
cout<<"\n the  swapped values in the function are"<<x<<"and"<<y;

}
Read Full

Pass by reference(swapping)

 Program for Passby reference-PARAMETER PASSING
#include<iostream.h>
#include<conio.h>
void swap(int *,int *);
void main()
{
int a,b;
cout<<"Enter any two numbers";
cin>>a>>b;
swap(&a,&b);
cout<<"\n the swapped valuesin the main funtion are"<<a<<"and"<<b;
getche();
}
void swap(int *x,int *y)
{
int t;
t=*x;
*x=*y;
*y=t;
cout<<"\n the  swapped values in the function are"<<  *x<<"and"<<     *y;

}

Read Full

Pyramid of Numbers

Have you ever tried doing some pyramid of numbers as in the given
    1
    123
     12345
     123
     1
The program here works for at most 7 digits
Program compiled and executed in turboc++ 
#include<iostream.h>
#include<conio.h>
void main()
{
long int i=0,n,j=1,k;
clrscr();
cout<<"Enter any Odd digit number\t";
R:cin>>n;
if((n%2)==0)
{
cout<<"The number you entered is not odd.Enter an odd number\n";
goto R;
}
else
{
cout<<"The Pyramid sequence is\n";
for(k=0;k<=((n-1)/2);k++)
{
for(int x=0;x<=(((n-1)/2)-k);x++)
cout<<" ";

i=(i*10)+(j+k);
cout<<i<<endl;
j++;
i=(i*10)+(j+k);
}

i=(i/10);
int y=1;
for(k=((n+1)/2);k<n;k++)
{
y++;
int z=y;
do
{
cout<<" ";
z--;
}while(z!=0);
i=(i/100);
cout<<i<<endl;
}
}
getch();
}
Read Full

Insertion Sort Using Functions

Insertion sort is a simple sorting algorithm: a comparison sort in which the sorted array (or list) is built one entry at a time. It is much less efficient on large lists than more advanced algorithms such as quicksort, heapsort, or merge sort. However, insertion sort provides several advantages:

  • Simple implementation
  • Efficient for (quite) small data sets
  • Adaptive (i.e., efficient) for data sets that are already substantially sorted: the time complexity is O(n + d), where d is the number of inversions
  • More efficient in practice than most other simple quadratic (i.e., O(n2)) algorithms such as selection sort or bubble sort; the best case (nearly sorted input) is O(n)
  • Stable; i.e., does not change the relative order of elements with equal keys
  • In-place; i.e., only requires a constant amount O(1) of additional memory space
  • Online; i.e., can sort a list as it receives it
Logic : Here, sorting takes place by inserting a particular element at the appropriate position, that’s why the name-  insertion sorting. In the First iteration, second element A[1] is compared with the first element A[0]. In the second iteration third element is compared with first and second element. In general, in every iteration an element is compared with all the elements before it. While comparing if it is found that the element can be inserted at a suitable position, then space is created for it by shifting the other elements one position up and inserts the desired element at the suitable position. This procedure is repeated for all the elements in the list.
If we complement the if condition in this program, it will give out the sorted array in descending order.
When humans manually sort something (for example, a deck of playing cards), most use a method that is similar to insertion sort.
Animation showing the algorithm for Insertion sort :
A brief view on how the logic Proceeds :



Program for Insertion Sort Compiled and Executed in turbo c++ 
#include<iostream.h>
#include<conio.h>
void insertionsort(int a[],int)   ;
void main()
{
int n,i,j,k,a[30];
cout<<"enter the no of elements you want to enter";
cin>>n;
cout<<"Enter the elements";
for(i=0;i<n;i++)
cin>>a[i];
insertionsort(a,n);
getch();
}
void insertionsort(int array[],int size)
{
int i, j, key;

for (j=1; j<size; j++)
{
key= array[j];
i=j-1;
while((i>=0)&&(array[i]>key))
{
array[i+1]= array[i];
i=i-1;
}
array[i+1]=key;
}
cout<<"sorted array is";
for(i=0;i<size;i++)
cout<<array[i]<<"\t";
}
Class Sorting algorithm
Data structure Array
Worst case performance О(n2)
Best case performance O(n)
Average case performance О(n2)
Worst case space complexity О(n) total, O(1) auxiliary
 
Read Full

Bubble Sorting

Bubble sort, also known as sinking sort, is a simple sorting algorithm that works by repeatedly stepping through the list to be sorted, comparing each pair of adjacent items and swapping them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted. The algorithm gets its name from the way smaller elements "bubble" to the top of the list. Because it only uses comparisons to operate on elements, it is a comparison sort. Although the algorithm is simple, it is not efficient for sorting large lists; other algorithms are better.

Performance:

Bubble sort has worst-case and average complexity both О(n2), where n is the number of items being sorted. There exist many sorting algorithms with substantially better worst-case or average complexity of O(n log n). Even other О(n2) sorting algorithms, such as insertion sort, tend to have better performance than bubble sort. Therefore, bubble sort is not a practical sorting algorithm when n is large.
                     The only significant advantage that bubble sort has over most other implementations, even quicksort, but not insertion sort, is that the ability to detect that the list is sorted is efficiently built into the algorithm. Performance of bubble sort over an already-sorted list (best-case) is O(n). By contrast, most other algorithms, even those with better average-case complexity, perform their entire sorting process on the set and thus are more complex. However, not only does insertion sort have this mechanism too, but it also performs better on a list that is substantially sorted (having a small number of inversions).

An Animated Example:



Program for Bubble sort compiled and executed in turbo C++  
#include<iostream.h>
#include<conio.h>
void swap(int &,int &);
void main()
{
int a[30],i,j,k;
clrscr();
cout<<"Enter the No of elements yo want to enter";
cin>>k;
cout<<"Now enter elements";
for(i=0;i<k;i++)
cin>>a[i];
for(i=0;i<k;i++)
{
for(j=0;j<k-i;j++)
{
if(a[j]>a[j+1])
{
int t=a[j];
a[j]=a[j+1];
a[j+1]=t;
}
}
}
cout<<"The sorted order is";
for(i=0;i<k;i++)
cout<<a[i]<<"\t";
getch();
} 
Buuble Sort-Overview
Class Sorting algorithm
Data structure Array
Worst case performance O(n2)
Best case performance O(n)
Average case performance O(n2)
Worst case space complexity O(1) auxiliary


Read Full

Best, worst and average cases of Performance

In computer science, best, worst and average cases of a given algorithm express what the resource usage is at least, at most and on average, respectively. Usually the resource being considered is running time, but it could also be memory or other resources.
In real-time computing, the worst-case execution time is often of particular concern since it is important to know how much time might be needed in the worst case to guarantee that the algorithm will always finish on time.
Average performance and worst-case performance are the most used in algorithm analysis. Less widely found is best-case performance, but it does have uses: for example, where the best cases of individual tasks are known, they can be used to improve the accuracy of an overall worst-case analysis. Computer scientists use probabilistic analysis techniques, especially expected value, to determine expected running times.
The terms are used in other contexts; for example the worst- and best-case outcome of a planned-for epidemic, worst-case temperature to which an electronic circuit element is exposed, etc. Where components of specified tolerance are used, devices must be designed to work properly with the worst-case combination of tolerances and external conditions.

Best Case Performance
The term best-case performance is used in computer science to describe the way an algorithm behaves under optimal conditions. For example, the best case for a simple linear search on a list occurs when the desired element is the first element of the list.

Examples

  • Linear search on a list of n elements. In the worst case, the search must visit every element once. This happens when the value being searched for is either the last element in the list, or is not in the list. However, on average, assuming the value searched for is in the list and each list element is equally likely to be the value searched for, the search visits only n/2 elements.
  • Insertion sort applied to a list of n elements, assumed to be all different and initially in random order. On average, half the elements in a list A1 ... Aj are less than element Aj+1, and half are greater. Therefore the algorithm compares the j+1-st element to be inserted on the average with half the already sorted sub-list, so tj = j/2. Working out the resulting average-case running time yields a quadratic function of the input size, just like the worst-case running time.
  • Quicksort applied to a list of n elements, again assumed to be all different and initially in random order. This popular sorting algorithm has an average-case performance of O(n log n), which contributes to making it a very fast algorithm in practice. But given a worst-case input, its performance degrades to O(n2).
Read Full

Thursday, August 11, 2011

Program using recursion to List all sub directories starting at a given path

#include <iostream>
#include <string>
#include <io.h>
 
using namespace std;
 
#define DIR "c:"
 
int rec_dir_list(string path) {
  static int count = 0;
  struct _finddata_t  c_file;
  long fh;
  
 
  string t_path = path;
  t_path += "\\*.*";
 
  if((fh=_findfirst(t_path.c_str(),&c_file)) != -1)
    while(_findnext(fh, &c_file) == 0)
      // ignore '.' and '..'
      if(strncmp(c_file.name, ".", 1) != 0
         && strncmp(c_file.name, "..", 2) != 0) {
        if((c_file.attrib & _A_SUBDIR) == _A_SUBDIR) {
          rec_dir_list(path + "\\" + c_file.name);
          cout << "DIR: " << path << "\\" << c_file.name << endl;
          count++;
        }
      }
 
  return count;
}
 
int main() {
 
  cout << "There are " << rec_dir_list(DIR)
       << " sub directories\n";
 
  return 0;
}
Read Full

Reading of file dynamically

#include <iostream>
#include <fstream.h>
 
int main() 
 {
    char inLine[128];
    char fname[24];
    ifstream inFile;
 
    cout << "Enter a file that contains text: ";
    cin >> fname;
 
    /* open the file */
    inFile.open(fname, ios::in);
 
    /* if opening didn't fail */
    if(!inFile.fail()) {
 
        while(!inFile.eof()) {
            inFile >> inLine;
            cout << inLine << endl;
        }
        
        inFile.close();
    } else 
        cout << "Error Opening File.";
 
    return 0;
}
Read Full