Sie sind auf Seite 1von 8

10.

Case Studies

1
Generation of Fibonacci
Number
#include <stdio.h>
#define SER 20
int main()
{int f[100];
int i=2;
f[0]=0; f[1]=1; /* f0 and f1 predefined*/
printf(“f0=%d\tf1=%d\t”, f[0], f[1]);

R. Subburaj, “Programming in C” © Vikas Publshing House Pvt. Ltd, New Delhi 2


Generation of Fibonacci
Number (Contd.)
while(i < SER)
{ f[i]=f[i-1] +f[i-2];
printf(“f%d=%d\t”, i, f[1]);
i++;
}
}

R. Subburaj, “Programming in C” © Vikas Publshing House Pvt. Ltd, New Delhi 3


Finding Kth smallest
element in a given set of
numbers
A set of numbers is given here, and required to
find the Kth smallest element. The numbers
can be arranged in ascending order in an
array, then the Kth smallest element is the
(K-1)th element in the array, since the 0th
element is the first smallest element, the 1st
element and so on.

R. Subburaj, “Programming in C” © Vikas Publshing House Pvt. Ltd, New Delhi 4


Finding Kth smallest
element in a given set of
numbers (contd.)
Step 1: Get the numbers.
Step 2: Sort them in ascending order.
Step 3: Ask for the K value.
Step 4: Print (K-1)st value.

Study example 51. Array is sent to find the


k th smallest element in the called function
find ()

R. Subburaj, “Programming in C” © Vikas Publshing House Pvt. Ltd, New Delhi 5


Sorting by Insertion
The algorithm for the insertion Sort is given below:
Int I, j, x, a[n];
for(I=1; I<=n-1; I++)
{ x=a[1];
j=I;
while (x<a [j-1]) && (j>0)
{a[j]=a[j-1];
j=j-1;
}
a[j]=x
}
Study the example given in page nos. 175-178 and
example 52

R. Subburaj, “Programming in C” © Vikas Publshing House Pvt. Ltd, New Delhi 6


Shell Sort
a) Elements far apart are compared first, i.e.,
elements separated by n/2 are compared. If
there are 8 elements in the array then in the
first instance, elements 1&5, 2&6, 3&7 and
4&8 are compared and inserted at the
appropriate places.
b) Next the separation is reduced by half . In
this case it is 2. Now there will be
comparisons and insertions between the
elements as given below: 1&3, 2&4, 3&5,
4&6, 5& 7, 6&8.
R. Subburaj, “Programming in C” © Vikas Publshing House Pvt. Ltd, New Delhi 7
Shell Sort (contd.)

c) Then the separation is divided by 2, which


means 1. Thus all elements will be sorted.
Algorithm for shell sort
for(sep=n/2; sep>0; sep=sep/2)
for(I=sep; I<n; I++)
for(j=I-sep; j>=0; j=j-sep)
{ while (a[j]>a[j+sep])
exchange}

R. Subburaj, “Programming in C” © Vikas Publshing House Pvt. Ltd, New Delhi 8

Das könnte Ihnen auch gefallen