DAA Lab Manual
DAA Lab Manual
(KCS-553)
Brief Theory:-A binary search will start by examining the middle item. If that item is the one we
are searching for, we are done. If it is not the correct item, we can use the ordered nature of the
list to eliminate half of the remaining items. If the item we are searching for is greater than
the middle item, we know that the entire lower half of the list as well as the middle item can be
eliminated from further consideration. The item, if it is in the list, must be in the upper half.
We can then repeat the process with the upper half. Start at the middle item and compare
it against what we are looking for. Again, we either find it or split the list in half, therefore
eliminating another large part of our possible search space.
Procedure:-Given an array A of n elements with values or records A0 ... An−1 and target
value T, the following subroutine uses binary search to find the index of T in A.
1. Set L to 0 and R to n − 1.
2. If L > R, the search terminates as unsuccessful. Set m (the position of the middle element) to the
floor of (L + R) / 2.
3. If Am < T, set L to m + 1 and go to step 2.
4. If Am > T, set R to m − 1 and go to step 2.
5. If Am = T, the search is done; return m.
Program:-
#include<stdio.h>
int main(){
int a[10],i,n,m,c,l,u;
return 0;
}
int mid,c=0;
if(l<=u){ mid=(l+u)/2;
if(m==a[mid]){
c=1;
}
else if(m<a[mid]){
return binary(a,n,m,l,mid-1);
}
else
return binary(a,n,m,mid+1,u);
}
else
return c;
}
Result:-
Unsuccessful searches
Θ(1) Θ (logn) Θ (Logn)
best average worst
Θ (logn)
Experiment-2
Brief Theory:- Linear search or sequential search is a method for finding a target value
within a list. It sequentially checks each element of the list for the target value until a
match is found or until all the elements have been searched. Linear search runs in at worst linear
time and makes at most n comparisons, where n is the length of the list
Procedure:-
1. LinearSearch(value, list)
2. if the list is empty, return item_not_found;
3. else
4. if the first item of the list has the desired value, return its location;
5. else return LinearSearch(value, remainder of the list)
Program:-
#include<stdio.h>
int main(){
int a[10],i,n,m,c=0;
printf("Enter the size of an array: ");
scanf("%d",&n);
printf("Enter the elements of the array: ");
for(i=0;i<=n-1;i++){
scanf("%d",&a[i]);
}
printf("Enter the number to be search: ");
scanf("%d",&m);
for(i=0;i<=n-1;i++){
if(a[i]==m){
c=1;
break;
}
}
if(c==0)
printf("The number is not in the list");
else
printf("The number is found");
return 0;
Results:
Enter the size of an array: 5
Enter the elements of the array: 4 6 8 0 3
Enter the number to be search: 0
The number is found
Viva-voce Questions
Brief Theory:- Insertion sort is a simple sorting algorithm that builds the final sorted array (or
list) one item 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:
Efficient for (quite) small data sets, much like other quadratic sorting algorithms
More efficient in practice than most other simple quadratic (i.e., O(n2)) algorithms such
as selection sort or bubble sort
Adaptive, i.e., efficient for data sets that are already substantially sorted: the time complexity is
O(nk) when each element in the input is no more than k places away from its sorted position
Stable; i.e., does not change the relative order of elements with equal keys
Procedure:-
1. for i ← 1 to length(A)-1
2. j ← i
3. while j > 0 and A[j-1] > A[j]
4. swap A[j] and A[j-1] 5.j
←j–1
6. end while
7. end for
Program:-
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int i,t,a[100],d,n;
printf("Enter The No. Of Elements\n");
scanf("%d",&n);
printf("Enter %d Integers\n",n);
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
for(i=1;i<=n-1;i++)
{
d=i;
while(d>0&&a[d]<a[d-1])
{ t=a[d];
a[d]=a[d-1];
a[d-1]=t;
d--;
}
}
printf("Sorted List in Ascending Order is:\n");
for(i=0;i<=n-1;i++)
{
printf("%d\t",a[i]);
}
getch();
}
Results:
Enter the No. of Elements: 5
Enter 5 integers: 11, 1, 14, 9, 4
Sorted List in Ascending Order Using Insertion Sort is: 1, 4, 9, 11, 14
Viva-voce Questions
Brief Theory:- Merge sort is based on the divide-and-conquer paradigm. Its worst- case
running time has a lower order of growth than insertion sort. Since we are dealing with sub
problems, we state each sub problem as sorting a sub array A[p .. r]. Initially, p = 1 and r = n, but
these values change as we recurs through sub problems. To sort A[p .. r]:
1. Divide Step
If a given array A has zero or one element, simply return; it is already sorted. Otherwise, split A[p
.. r] into two subarrays A[p .. q] and A[q + 1 .. r], each containing about half of the elements of A[p
.. r]. That is, q is the halfway point of A[p .. r].
2. Conquer Step
Conquer by recursively sorting the two subarrays A[p .. q] and A[q + 1 .. r].
3. Combine Step
Combine the elements back in A[p .. r] by merging the two sorted subarrays A[p .. q] and A[q + 1
.. r] into a sorted sequence. To accomplish this step, we will define a procedure MERGE (A, p, q,
r).
Procedure:-
To sort the entire sequence A[1 .. n], make the initial call to the procedure MERGE-SORT (A, 1,
n).
MERGE-SORT (A, p, r)
#include <stdio.h>
#include<conio.h>
void mergesort(int arr[], int l, int h);
void main(void)
{
int array[100],n,i = 0;
clrscr();
printf("\t\t\tMerge Sort\n\n\n\n");
printf("Enter the number of elements to be sorted: ");
scanf("%d",&n);
printf("\nEnter the elements to be sorted: \n");
for(i = 0 ; i < n ; i++ )
{
printf("\tArray[%d] = ",i);
scanf("%d",&array[i]);
}
printf("\nBefore Mergesort:");
for(i = 0; i < n; i++)
{
printf("%4d", array[i]);
} printf("\n");
mergesort(array, 0, n - 1);
printf("\nAfter Mergesort:");
for(i = 0; i < n; i++)
{
printf("%4d", array[i]);
}
printf("\n");
getch();
}
void mergesort(int arr[], int l, int h)
{
int i = 0;
int length = h - l + 1;
int pivot = 0;
int merge1 = 0;
int merge2 = 0;
int temp[100];
if(l == h)
return;
pivot = (l + h) / 2;
mergesort(arr, l, pivot);
mergesort(arr, pivot + 1, h);
for(i = 0; i < length; i++)
{
temp[i] = arr[l + i];
}
merge1 = 0;
merge2 = pivot - l + 1;
for(i = 0; i < length; i++)
{
if(merge2 <= h - l)
{
if(merge1 <= pivot - l)
{
if(temp[merge1] > temp[merge2])
{
arr[i + l] = temp[merge2++];
}
else
{
arr[i + l] = temp[merge1++];
}
}
else
{
arr[i + l] = temp[merge2++];
}
}
else
{
arr[i + l] = temp[merge1++];
}
}
}
Results:
Enter the No. of Elements to be sorted: 7
Enter the elements to be sorted: 11, 1, 14, 4, 18, 16, 9.
Sorted List in Ascending Order Using Merge Sort is: 1, 4, 9, 11, 14, 16, 18.
The algorithm divides the input list into two parts: the sublist of items already sorted, which is built
up from left to right at the front (left) of the list, and the sublist of items remaining to be sorted that
occupy the rest of the list. Initially, the sorted sublist is empty and the unsorted sublist is the entire
input list. The algorithm proceeds by finding the smallest (or largest, depending on sorting order)
element in the unsorted sublist, exchanging (swapping) it with the leftmost unsorted element
(putting it in sorted order), and moving the sublist boundaries one element to the right.
Procedure:-
SELECTION_SORT (A)
for i ← 1 to n-1 do
min j ← i;
min x ← A[i]
for j ← i + 1 to n do
If A[j] < min x then
min j ← j
min x ← A[j]
A[min j] ← A [i]
A[i] ← min x
Program:-
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int i,position,swap,a[100],d,n;
printf("Enter The No. Of Elements\n");
scanf("%d",&n);
printf("Enter %d Integers\n",n);
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
for(i=0;i<(n-1);i++)
{ position=i;
for(d=c+1;d<n;d++)
{
if(array[position]>array[d])
position=d;
}
if(position!=i)
{ swap=a[i];
a[i]=a[position];
a[position]=swap;
}
}
printf("Sorted List in Ascending Order is:\n");
for(i=0;i<=n;i++)
{
printf("%d\t",a[i]);
}
getch();
}
Results:
Enter the No. of Elements to be sorted: 5
Enter 5 integers: 70, 12, 50, 20, 10
Sorted List in Ascending Order Using Selection Sort is: 10, 12, 20, 50, 70
Brief Theory:- Quicksort is a divide and conquer algorithm. Quicksort first divides a large array
into two smaller sub-arrays: the low elements and the high elements. Quicksort can then recursively
sort the sub-arrays.
Procedure:-
#include<stdio.h
#include<conio.h>
void quicksort(int [10],int,int);
void main()
{
clrscr();
int a[20],n,i;
printf("Enter size of the array:\n");
scanf("%d",&n);
printf("Enter %d elements:\n",n);
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
quicksort(a,0,n-1);
printf("Sorted elements:\n ");
for(i=0;i<n;i++)
{
printf("\t%d",a[i]);
}
getch();
}
void quicksort(int a[10],int first,int last)
{
int pivot,j,temp,i;
if(first<last)
{
pivot=first;
i=first;
j=last;
while(i<j)
{
while(a[i]<=a[pivot]&&i<last)
i++;
while(a[j]>a[pivot])
j--;
if(i<j)
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
temp=a[pivot];
a[pivot]=a[j];
a[j]=temp;
quicksort(a,first,j
-1);
quicksort(a,j+1,l
ast);
}
}
Results:
Enter the No. of Elements to be sorted: 5
Enter 5 integers: 70, 12, 50, 20, 10
Sorted List in Ascending Order Using Quick Sort is: 10, 12, 20, 50, 70
Viva-voce Questions
Procedure:-
1. Call the buildMaxHeap() function on the list. Also referred to as heapify(), this builds a heap
from a list in O(n) operations.
2. Swap the first element of the list with the final element. Decrease the considered range of the
list by one.
3. Call the Adjust() function on the list to sift the new first element to its appropriate index in
the heap.
4. Go to step (2) unless the considered range of the list is one element.
Program:-
#include<stdio.h>
#include<conio.h>
void heapsort(int[], int);
void heapify(int[], int);
void adjust(int[], int);
int main()
{
int array[50],n,i;
clrscr();
printf("Enter the no. of elements to be sorted:\n ");
scanf("%d",&n);
printf("Enter %d elements: \n",n);
for(i=0 ; i<n ; i++)
{
scanf("%d",&array[i]);
heapsort(array,n);
printf("Sorted list in ascending order using heap sort is:\n");
for(i = 0; i < n; i++)
{
printf("%d\t", array[i]);
}
printf("\n");
getch();
return 0;
}
void heapsort(int array[], int n)
{
int i,t;
heapify(array,n);
for(i=n-1 ; i>0 ; i--)
{
t = array[0];
array[0] = array[i];
array[i] = t;
adjust(array,i);
}
}
void heapify(int array[], int n)
{
int item,i,j,k;
for(k=1 ; k<n ; k++)
{
item = array[k];
i = k;
j = (i-1)/2;
while( (i>0) && (item>array[j]) )
{
array[i] = array[j];
i = j;
j = (i-1)/2;
}
array[i] = item;
}
}
void adjust(int array[], int n)
{
int item,i,j;
j = 0;
item = array[j];
i = 2*j+1;
while(i<=n-1)
{
if(i+1 <= n-1)
if(array[i] < array[i+1])
i++;
if(item < array[i])
{
array[j] = array[i];
j = i;
i = 2*j+1;
} else
break;
}
array[j] = item;
}
Results:
Enter the No. of Elements to be sorted: 5
Enter 5 integers: 70, 12, 50, 20, 15
Sorted List in Ascending Order Using Heap Sort is: 12, 15, 20, 50, 70
Viva-voce Questions
1. What is the average case complexity for heap sort algorithm?
O(n logn)
Procedure:-
1. // Input:
2. // Values (stored in array v)
3. // Weights (stored in array w)
4. // Number of distinct items (n)
5. // Knapsack capacity (W)
6. for j from 0 to W do:
7. m[0, j] := 0
8. for i from 1 to n do:
9. for j from 0 to W do:
10. if w[i-1] > j then:
11. m[i, j] := m[i-1, j]
12. else:
13. m[i, j] := max(m[i-1, j], m[i-1, j-w[i-1]] + v[i-1])
Program:-
#include<stdio.h>
#include<conio.h>
void knapsack(int n, float weight[], float profit[], float capacity)
{
float x[20], tp = 0;
int i, j, u;
u = capacity;
for (i = 0; i < n; i++)
x[i] = 0.0;
for (i = 0; i < n; i++)
{
if (weight[i] > u)
break;
else
{
x[i] = 1.0;
tp = tp + profit[i];
u = u - weight[i];
}
}
if (i < n)
x[i] = u / weight[i];
tp = tp + (x[i] * profit[i]);
printf("\nThe result vector is:- ");
for (i = 0; i < n; i++)
printf("%f\t", x[i]);
printf("\nMaximum profit is:- %f", tp);
}
void main()
{
clrscr();
float weight[20], profit[20], capacity;
int num, i, j;
float ratio[20], temp;
printf("\nEnter the no. of objects:- ");
scanf("%d", &num);
printf("\nEnter the weights and profits of each object:- ");
for (i = 0; i < num; i++)
{
scanf("%f %f", &weight[i], &profit[i]);
}
printf("\nEnter the capacity of knapsack:- ");
scanf("%f", &capacity);
for (i = 0; i < num; i++)
{
ratio[i] = profit[i] / weight[i];
}
for (i = 0; i < num; i++)
{
for (j = i + 1; j < num; j++)
{
if (ratio[i] < ratio[j])
{
temp = ratio[j];
ratio[j] = ratio[i];
ratio[i] = temp;
temp=weight[j];
weight[j] = weight[i];
weight[i] = temp;
temp = profit[j];
profit[j] = profit[i];
profit[i] = temp;
}
}
}
knapsack(num, weight, profit, capacity);
getch();
}
Results:
3, 5
5, 15
7, 7
1, 6
4, 18
1, 3
Enter the capacity of knapsack: - 15
The result vector is: - 1.000000 1.000000 1.000000 1.000000 1.000000 0.666667 0.000000
Maximum profit is: - 55.333332
Viva –Voce Questions
Objective: - Program to find the minimum spanning tree using Kruskal’s algorithm.
Procedure:-
KRUSKAL(G):
1A=∅
foreach v ∈ G.V:
MAKE-SET(v)
foreach (u, v) in G.E ordered by weight(u, v), increasing:
if FIND-SET(u) ≠ FIND-SET(v):
6 A = A ∪ {(u, v)}
7 UNION(u, v)
8 return A
Program:-
#include<stdio.h>
#include<conio.h>
#define INF 0
char vertex[10];
int wght[10][10];
int span_wght[10][10];
int source;
struct Sort
{
int v1,v2;
int weight;
}que[20];
int n,ed,f,r;
int cycle(int s,int d)
{
int j,k;
if(source==d)
return 1; for(j=0;j<n;j++)
if(span_wght[d][j]!=INF && s!=j)
{
if(cycle(d,j))
return 1;
}
return 0;
}
void build_tree()
{
int i,j,w,k,count=0;
for(count=0;count<n;f++)
{ i=que[f].v1;
j=que[f].v2;
w=que[f].weight;
span_wght[i][j]=span_wght[j][i]=w;
source=i;
k=cycle(i,j);
if(k)
span_wght[i][j]=span_wght[j][i]=INF;
else
count++;
}
}
void swap(int *i,int *j)
{
int t;
t=*i;
*i=*j;
*j=t;
}
void main()
{
int i,j,k=0,temp;
int sum=0;
clrscr();
printf("\n\tEnter the No. of Nodes : ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\n\t\tLIST OF EDGES\n\n");
for(i=0;i<n;i++)
for(j=i+1;j<n;j++)
if(span_wght[i][j]!=INF)
{
printf("\n\t\t%c ------- %c = %d ",vertex[i],vertex[j],span_wght[i][j]);
sum+=span_wght[i][j];
}
printf("\n\n\t\tTotal Weight : %d ",sum);
getch();
}
Results:
Original Graph Weight Matrix
Weight Matrix
0 4 8 6 7
4 0 2 9 0
8 2 0 8 5
6 9 8 0 3
7 0 5 3 0
Total weight = 14
Viva-voce Questions
1. What is graph?
A graph is a pictorial representation of a set of objects where some pairs of objects are
connected by links. The interconnected objects are represented by points termed as vertices,
and the links that connect the vertices are called edges.
Brief Theory:-The Travelling Salesman Problem describes a salesman who must travel between
N cities. The order in which he does so is something he does not care about, as long as he visits
each one during his trip, and finishes where he was at first. Each city is connected to other close by
cities, or nodes, by airplanes, or by road or railway. Each of those links between the cities has one
or more weights (or the cost) attached. The cost describes how "difficult" it is to traverse this edge
on the graph, and may be given, for example, by the cost of an airplane ticket or train
ticket, or perhaps by the length of the edge, or time required to complete the traversal. The
salesman wants to keep both the travel costs, as well as the distance he travels as low as possible.
Procedure:-
Program:-
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int a[10][10],visited[10],n,cost=0;
void get()
{
int i,j;
printf("\n\nEnter Number of Cities: ");
scanf("%d",&n);
printf("\nEnter Cost Matrix: \n");
for( i=0;i<n;i++)
{
printf("\n Enter Elements of Row # : %d\n",i+1);
for( j=0;j<n;j++)
scanf("%d",&a[i][j]);
visited[i]=0;
}
printf("\n\nThe Cost Matrix is:\n");
for( i=0;i<n;i++)
{ printf("\n\n");
for(j=0;j<n;j++)
printf("\t%d",a[i][j]);
}
}
void mincost(int city)
{
int i,ncity,least(int city);
visited[city]=1;
printf("%d ===> ",city+1);
ncity=least(city);
if(ncity==999)
{ ncity=0;
printf("%d",ncity+1);
cost+=a[city][ncity];
return;
}
mincost(ncity);
}
int least(int c)
{
int i,nc=999;
int min=999,kmin;
for(i=0;i<n;i++)
{
if((a[c][i]!=0)&&(visited[i]==0))
if(a[c][i]<min)
{
min=a[i][0]+a[c][i];
kmin=a[c][i];
nc=i;
}
}
if(min!=999)
cost+=kmin;
return nc;
}
void put()
{
printf("\n\nMinimum cost:");
printf("%d",cost);
}
void main()
{
clrscr();
get();
printf("\n\nThe Path is:\n\n");
mincost(0);
put();
getch();
}
Results:
Travelling Salesman Problem describes a salesman who must travel between N cities. The order
in which he does so is something he does not care about, as long as he visits each one during
his trip, and finishes where he was at first. Each city is connected to other close by
cities, or nodes, by airplanes, or by road or railway. Each of those links between the cities has
one or more weights (or the cost) attached. The cost describes how "difficult" it is to traverse
this edge on the graph, and may be given, for example, by the cost of an airplane ticket or train
ticket, or perhaps by the length of the edge, or time required to complete the traversal. The
salesman wants to keep both the travel costs, as well as the distance he travels as low as
possible.
3. Let a complete graph G has n vertices and e edges. What will be the value of e in terms
of vertices n?
e = n (n-1)/2
4. Define forest.
Collection of sub trees that are obtained when root node is eliminated is known as forest
Brief Theory:-In this problem or puzzle, N queens will be given and the challenge is to place all
of them in N x N chessboard so that no two queens are in attacking position. What that means is
we need to find the configuration of N queens where any of the two queens do not share a row,
column and diagonal paths. One of the better and elegant solutions to this puzzle is
‘backtracking algorithm’.
Procedure:-
1. Place the queens column wise, start from the left most column
2. If all queens are placed.
1. return true and print the solution matrix.
3. Else
1. Try all the rows in the current column.
2. Check if queen can be placed here safely if yes mark the current cell in solution
matrix as 1 and try to solve the rest of the problem recursively.
3. If placing the queen in above step leads to the solution return true.
4. If placing the queen in above step does not lead to the solution , BACKTRACK,
mark the current cell in solution matrix as 0 and return false.
4. If all the rows are tried and nothing worked, return false and print NO SOLUTION.
Program:-
#include<stdio.h>
#include<conio.h>
#include<math.h>
char a[10][10];
int n;
void printmatrix()
{
int i, j;
printf("\n");
for (i = 0; i < n; i++)
{
{
printf("\nThe solution is:- ");
printmatrix();
}
}
void main()
{
clrscr();
int i, j;
printf("\nEnter the no. of queens:- ");
scanf("%d", &n);
for (i = 0; i < n; i++)
for (j = 0; j < n; j++)
a[i][j] = '.';
nqueen(0);
getch();
}
Results:
Enter the no. of queens: - 4
The solution is: -
. Q . .
. . . Q
Q . . .
. . Q .
The solution is: -
. . Q .
Q . . .
. . . Q
. Q . .
Viva-voce Questions
The problem is to place n queens on an n by n chessboard so that no two queens attack each
other by being in the same row or same column or on the same diagonal.
Shell sort, also known as Shell sort or Shell’s method, is an in-place comparison sort. It can either
be seen as a generalization of sorting by exchange (bubble sort) or sorting by insertion (insertion
sort). The method starts by sorting elements far apart from each other and progressively reducing the
gap between them. Starting with far apart elements can move some out-of-place elements into
position faster than a simple nearest neighbor exchange. Here is the source code of the C program to
sort integers using Shell Sort technique. The C program is successfully compiled and run on a Linux
system. The program output is also shown below.
2. #include <stdio.h>
3. void shellsort(int arr[], int num) 4.
{
5. int i, j, k, tmp;
6. for (i = num / 2; i > 0; i = i / 2)
7. {
8. for (j = i; j < num; j++)
9. {
10. for(k = j - i; k >= 0; k = k - i)
11. {
12. if (arr[k+i] >= arr[k])
13. break;
14. else
15. {
16. tmp = arr[k];
17. arr[k] = arr[k+i];
18. arr[k+i] = tmp;
19. }
20. }
21. }
22. }
23. }
24. int main()
25. {
26. int arr[30];
27. int k, num;
28. printf("Enter total no. of elements : ");
29. scanf("%d", &num);
30. printf("\nEnter %d numbers: ", num); 31.
32. for (k = 0 ; k < num; k++)
33. {
34. scanf("%d", &arr[k]);
35. }
36. shellsort(arr, num);
37. printf("\n Sorted array is: ");
38. for (k = 0; k < num; k++)
39. printf("%d ", arr[k]);
40. return 0;
41. }
Input/output
Viva-voce Questions
Q.1 What is shell sort
Shell sort, also known as Shell sort or Shell’s method, is an in-place comparison sort. It can either
be seen as a generalization of sorting by exchange (bubble sort) or sorting by insertion (insertion
sort).
Worst case time complexity is O(n2) and best-case complexity is O(n log(n)).
Experiment-13
Bubble sort is also known as sinking sort. This algorithm compares each pair of adjacent items and
swaps them if they are in the wrong order, and this same process goes on until no swaps are
needed. In the following program we are implementing bubble sort in C language. In this program
user would be asked to enter the number of elements along with the element values and then the
program would sort them in ascending order by using bubble sorting algorithm logic.
#include<stdio.h>
int main(){
for(i=0;i<count;i++)
scanf("%d",&number[i]);
return 0;
}
Output:
Viva-voce Questions
Bubble sort is also known as sinking sort. This algorithm compares each pair of adjacent items and
swaps them if they are in the wrong order, and this same process goes on until no swaps are
needed. In the following program we are implementing bubble sort in C language
Experiment -14
Counting sort algorithm is a sorting algorithm which do not involve comparison between elements
of an array1.
First of all I am reading n elements in array a[]. While reading the array elements I have also
calculated the maximum element.
2. Now the actual sorting is done in counting_sort() function. Here I am counting the occurrence of
each element in the array a[] and then storing it at the index equal to the value of that element. For
example occurrence of element 5 will be stored at index 5, occurrence of element 9 will be stored
at index 9 and so on.
3. As the value at each index in count[] array is the occurrence of that index or element, so the
elements are printed in ascending order by printing each index number of times equal to its
corresponding value.
1 #include<stdio.h>
2
3 void counting_sort(int a[],int n,int max)
4 {
5 int count[50]={0},i,j;
6
7 for(i=0;i<n;++i)
8 count[a[i]]=count[a[i]]+1;
9
10 printf("\nSorted elements are:");
11
12 for(i=0;i<=max;++i)
13 for(j=1;j<=count[i];++j)
14 printf("%d ",i);
15 }
16
17 int main()
18 {
19 int a[50],n,i,max=0;
20 printf("Enter number of elements:");
21 scanf("%d",&n);
22 printf("\nEnter elements:")
23
for(i=0;i<n;++i)
{
scanf("%d",&a[i]);
24 if(a[i]>max)
25 max=a[i];
26 }
27
28 counting_sort(a,n,max);
29 return 0;
30 }
Output
Viva-voce Questions
Counting Sort. Counting sort is a sorting technique based on keys between a specific range. It
works by counting the number of objects having distinct key values (kind of hashing). Then doing
some arithmetic to calculate the position of each object in the output sequence.