Download as pdf or txt
Download as pdf or txt
You are on page 1of 35

Analysis and Design of Algorithms (3150703)

PRACTICAL – 1

Implement all possible flavors of Bubble sort. Display number of


comparisons taken by the same. Also do time analysis.

About Bubble Sort:

Bubble sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent
elements if they are in wrong order.
There are mainly three flavors of bubble sort.

l. Classical
2. Semi-optimized
3. Optimized

How Bubble Sort Works?


Bubble sort uses multiple passes (scans) through an array.
In each pass, bubble sort compares the adjacent elements of the array.
It then swaps the two elements if they are in the wrong order.
In each pass, bubble sort places the next largest element to its proper position.
In short, it bubbles down the largest element to its correct position. Algorithm for
simple bubble sort:

Algorithm ClassicalBubbleSort(A,N) where A is an array of N elements.


Step-I : Read A with N elements
Step-2: for to N-l for(j I to N-l)
then temp=A[j]

(end of is structure)
(end of inner loop)
(end of outer loop)
Step 3: Print the sorted sequence(values of array A)
Step 4: Stop/Return/End of algorithm

Algorithm SemiOptimizedBubbleSort(A,N) where A is an array of N elements.


Step-I : Read A with N elements Step-2: for to N-l for(j I to
N- I -i) //Decreasing iteration in each pass then
temp=A[j]

BE-III (Semester V) IT 210450116021 1


Analysis and Design of Algorithms (3150703)

(end of is structure)
(end of inner loop)
(end of outer loop)
Step 3: Print the sorted sequence(values of array A)
Step 4: Stop/Return/End of algorithm

Algorithm OptimizedBubbleSort(A,N) where A is an array of N elements.


Step-I : Read A with N elements
Step-2: for i=l to N-l for(j=l to N- I -i) //Decreasing iteration
in each pass then temp=ALj]

Setting the flag to 1 if swapping occurs


(end of is structure) (end of inner loop) if(flag==0)
then //no swapping occured break flag=0
//resetting the flag to 0 for next pass (end of outer
loop)
Step 3: Print the sorted sequence(values of array A)
Step 4: Stop/Return/End of algorithm

Time Complexity
Best Case O(n)
Average Case 0012)

C Code:

//210450116021_KALP_PATEL

#include <stdio.h>
#include <sys/time.h>
int bubble(int [],int); //Classical
int bubble1(int [],int); //Semi-optimised
int bubble2(int [],int); //Optimised
int main()
{
int a[100],i,n,t1,t2,t3,t4,t5,t6;
printf("How many elements you want to sort: ");
scanf("%d",&n);
printf("Enter the %d elements: ",n);
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);

BE-III (Semester V) IT 210450116021 2


Analysis and Design of Algorithms (3150703)

}
struct timeval tt;
struct timezone tz;
gettimeofday(&tt,&tz);
t1=tt.tv_usec;
bubble(a,n); //Classic function called
gettimeofday(&tt,&tz);
t2=tt.tv_usec;
printf("Time taken by Classical Bubble sort = %d \n",t2-t1);
gettimeofday(&tt,&tz);
t3=tt.tv_usec;
bubble1(a,n); //Semi-optimised function called
gettimeofday(&tt,&tz);
t4=tt.tv_usec;
printf("Time taken by Semi optimised Bubble sort = %d \n", t4-t3);
gettimeofday(&tt,&tz);
t5=tt.tv_usec;
bubble2(a,n); //Optimised function called
gettimeofday(&tt,&tz);
t6=tt.tv_usec;
printf("Time taken by Optimised Bubble sort = %d \n",t6-t5);
return 1;
}
int bubble(int a[],int n)
{
int j,k,temp;
for(j=0;j<n-1;j++)
{
for(k=0;k<n-1;k++)
{
if(a[k]>a[k+1])
{
//Swapping
temp=a[k];
a[k]=a[k+1];
a[k+1]=temp;
}
}
}
printf("The Sorted elements are: ");
for(j=0;j<n;j++)
{
printf(" %d ",a[j]); //Printing the sorted elements
}
printf("\n");
return 1;

BE-III (Semester V) IT 210450116021 3


Analysis and Design of Algorithms (3150703)

}
int bubble1(int a[],int n)
{
int j,k,temp;
for(j=0;j<n-1;j++)
{
for(k=0;k<n-j-1;k++) //Descreasing iteration in each pass
{
if(a[k]>a[k+1])
{
temp=a[k];
a[k]=a[k+1];
a[k+1]=temp;
}
}
}
printf("\nThe Sorted elements are: ");
for(j=0;j<n;j++)
{
printf(" %d ",a[j]); //Printing the sorted elements
}
printf("\n");
return 1;
}
int bubble2(int a[],int n)
{
int j,k,temp;
int flag=0;
for(j=0;j<n-1;j++)
{
for(k=0;k<n-j-1;k++)
{
if(a[k]>a[k+1])
{
temp=a[k];
a[k]=a[k+1];
a[k+1]=temp;
flag=1; //Whenever swapping occurs flag is set to 1
}
}
if(flag==0) //If no swapping occurs then the array is already sorted hence break the loop
break;
flag=0; //Resetting the flag to 0 for next pass
}
printf("\nThe Sorted elements are: ");
for(j=0;j<n;j++)

BE-III (Semester V) IT 210450116021 4


Analysis and Design of Algorithms (3150703)

{
printf(" %d ",a[j]); //Printing the sorted elements
}
printf("\n");
return 1;
}

Input/Output:

BE-III (Semester V) IT 210450116021 5


Analysis and Design of Algorithms (3150703)

PRACTICAL – 2

Implement Insertion sort with time analysis.


About Insertion Sort:

Insertion sort is a simple sorting algorithm that works similar to the way you sort playing cards
in your hands. The array is virtually split into a sorted and an unsorted part. Values from the
unsorted part are picked and placed at the correct position in the sorted part.
Characteristics of Insertion Sort:
This algorithm is one of the simplest algorithm with simple implementation
Basically, Insertion sort is efficient for small data values
Insertion sort is adaptive in nature, i.e. it is appropriate for data sets which are already partially
sorted.

Algorithm:
Step 1 — If the element is the first one, it is already sorted.
Step 2 Move to next element
Step 3 — Compare the current element with all elements in the sorted array
Step 4 If the element in the sorted array is smaller than the current element, iterate to the
next element. Otherwise, shift all the greater element in the array by one position
towards the right
Step 5 — Insert the value at the correct position
Step 6 — Repeat until the complete list is sorted

Example: array[l: {12, 11, 13, 5, 6}


12 11 13 5 6

First Pass:
Initially, the first two elements of the array are compared in insertion sort.
12 11 13 5 6
Here, 12 is greater than 1 1 hence they are not in the ascending order and 12 is not at its correct position.
Thus, swap 11 and 12.
So, for now 1 1 is stored in a sorted sub-array.
11 12 13 5 6

Second Pass:
Now, move to the next two elements and compare them
11 12 13 5 6
Here, 13 is greater than 12, thus both elements seems to be in ascending order, hence, no swapping will
occur. 12 also stored in a sorted sub-array along with 11

BE-III (Semester V) IT 210450116021 6


Analysis and Design of Algorithms (3150703)

Third Pass:
Now, two elements are present in the sorted sub-array which are 1 1 and 12
Moving forward to the next two elements which are 13 and 5
11 12 13 5 6
Both 5 and 13 are not present at their correct place so swap them
11 12 5 13 6
After swapping, elements 12 and 5 are not sorted, thus swap again
11 5 12 13 6
Here, again 1 1 and 5 are not sorted, hence swap
again 5 11 12 13 6 here, it is
at its correct position

Fourth Pass:
Now, the elements which are present in the sorted sub-array are 5, Il and 12
Moving to the next two elements 13 and 6
5 11 12 13 6
Clearly, they are not sorted, thus perform swap between both
5 11 12 6 13
Now, 6 is smaller than 12, hence, swap again
5 11 6 12 13
Here, also swapping makes 1 1 and 6 unsorted hence, swap
again 5 6 11 12 13
Finally, the array is completely sorted.

This algorithm has a worst-case time complexity of O(n2).

C Code:

//210450116021_KALP_PATEL

#include<stdio.h>
#include<sys/time.h>
int method1(int[],int);
int main()
{
int a[100],n,i,t1,t2;
printf("Enter The number of elements in Array: ");
scanf("%d",&n);
printf("Enter the values: ");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
struct timeval tt;
struct timezone tz;

BE-III (Semester V) IT 210450116021 7


Analysis and Design of Algorithms (3150703)

gettimeofday(&tt,&tz);
t1=tt.tv_usec;
method1(a,n);
gettimeofday(&tt,&tz);
t2=tt.tv_usec;
printf("Time taken by Insertion sort = %d \n",t2-t1);
return 1;
}
int method1(int a[],int n)
{
int i,j,temp;
for(i=1;i<n;i++)
{
temp=a[i];
j=i-1;
while(j>=0 && a[j]>temp)
{
a[j+1]=a[j];
j--;
}
a[j+1]=temp;
}
printf("The sorted Array is :");
for(i=0;i<n;i++)
{
printf(" %d ",a[i]);
}
printf("\n");
}

Input/Output:

BE-III (Semester V) IT 210450116021 8


Analysis and Design of Algorithms (3150703)

PRACTICAL – 3

Implement Selection sort with time analysis.


The selection sort algorithm sorts an array by repeatedly finding the minimum element
(considering ascending order) from the unsorted part and putting it at the beginning.
The algorithm maintains two subarrays in a given array.
The subarray which already sorted.
The remaining subarray was unsorted.
In every iteration of the selection sort, the minimum element (considering ascending order) from
the unsorted subarray is picked and moved to the sorted subarray.

Algorithm for Selection Sort:


Step 1 — Set min to the first location
Step 2 Search the minimum element in the array
Step 3 — swap the first location with the minimum value in the array
Step 4 — assign the second element as min.
Step 5 — Repeat the process until we get a sorted array.

Example: array[l = {64, 25, 12, 22, 11}

First pass:
For the first position in the sorted array, the whole array is traversed from index 0 to 4 sequentially. The
first position where 64 is stored presently, after traversing whole array it is clear that 1 1 is the lowest
value.
64 25 12 22 11
Thus, replace 64 with 11. After one iteration 1 1, which happens to be the least value in the array, tends to
appear in the first position of the sorted list. 11 25 12 22 64

Second Pass:
For the second position, where 25 is present, again traverse the rest of the array in a sequential manner.
11 25 12 22 64
After traversing, we found that 12 is the second lowest value in the array and it should appear at the
second place in the array, thus swap these values. 11 12 25 22 64

Third Pass:
Now, for third place, where 25 is present again traverse the rest of the array and find the third least value
present in the array.
11 12 25 22 64
While traversing, 22 came out to be the third least value and it should appear at the third place in the
array, thus swap 22 with element present at third position. 11 12 22 25 64

Fourth pass:
Similarly, for fourth position traverse the rest of the array and find the fourth least element in the array

BE-III (Semester V) IT 210450116021 9


Analysis and Design of Algorithms (3150703)

As 25 is the 4th lowest value hence, it will place at the fourth position.
11 12 22 25 64
Fifth Pass:
At last the largest value present in the array automatically get placed at the last position in the array The
resulted array is the sorted array.
11 12 22 25 64
Time Complexity: The time complexity of Selection Sort is O(n2) as there are two nested
loops

C Code:

//210450116021_KALP_PATEL

#include<stdio.h>
#include<sys/time.h>
int method1(int[],int);
int main()
{
int a[100],n,i,t1,t2;
printf("Enter The number of elements in Array: ");
scanf("%d",&n);
printf("Enter the values: ");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
struct timeval tt;
struct timezone tz;
gettimeofday(&tt,&tz);
t1=tt.tv_usec;
method1(a,n);
gettimeofday(&tt,&tz);
t2=tt.tv_usec;
printf("Time taken by Selection sort = %d \n",t2-t1);
return 1;
}
int method1(int a[],int n)
{
int i,j,temp,min;
for(i=0;i<n-1;i++)
{
min=i;
for(j=i+1;j<n;j++)
{

BE-III (Semester V) IT 210450116021 10


Analysis and Design of Algorithms (3150703)

if(a[j]<a[min])
{
min=j;
}
}
if(min!=i)
{
temp=a[min];
a[min]=a[i];
a[i]=temp;
}
}
printf("The sorted Array is: ");
for(i=0;i<n;i++)
{
printf(" %d ",a[i]);
}
printf("\n");
return 1;
}

Input/Output:

BE-III (Semester V) IT 210450116021 11


Analysis and Design of Algorithms (3150703)

PRACTICAL – 4

Implement a program to find factorial of given number using iterative and


recursive method. Compare the same
C Code:

/* Practical-4: Implement a program to find factorial of given number using iterative and
recursive method. Compare the same */
//210450116021_KALP_PATEL

#include <stdio.h>
int fact_iteration(int);
int fact_recursion(int);

int i,N=5,fact1,fact2,fact=1;
int main()
{

fact1=fact_iteration(N);
printf("Factorial Of %d using iteration:%d \n",N,fact1);
fact2=fact_recursion(N);
printf("Factorial Of %d using Recursion:%d ",N,fact2);
}
int fact_iteration(int N)
{

for(i=1;i<=N;i++)
fact=fact*i;
return fact;
}

int fact_recursion(int N)
{
int fact;
if(N==0 || N==1)
return 1;
else
fact=N*fact_recursion(N-1);
return fact;
}

BE-III (Semester V) IT 210450116021 12


Analysis and Design of Algorithms (3150703)

Input/Output:

BE-III (Semester V) IT 210450116021 13


Analysis and Design of Algorithms (3150703)

PRACTICAL – 5

Implement a program for finding minimum/maximum number from a given


list with DAQ strategy.

Algorithm:
Example:

BE-III (Semester V) IT 210450116021 14


Analysis and Design of Algorithms (3150703)

C Code:

//Max number
//210450116021_KALP_PATEL

#include <stdio.h>
int findmaxDAC(int a[],int beg,int end);
int main()
{
int a[10]={5,50,55,15,25,65,35,75,100,58};
printf("Maximum number from array: %d",findmaxDAC(a,0,9));
}
int findmaxDAC(int a[],int beg,int end)
{
int mid,max1,max2;
if(beg==end)
return a[beg];
else if(beg==end-1)
if(a[beg]>=a[end])
return a[beg];
else
return a[end];
else
mid=(beg+end)/2;
max1 = findmaxDAC(a,beg,mid);
max2 = findmaxDAC(a,mid+1,end);
if(max1>=max2)
return max1;
else
return max2;
}

Input/Output:

BE-III (Semester V) IT 210450116021 15


Analysis and Design of Algorithms (3150703)

PRACTICAL – 6

Implement Linear searching and Binary searching. Do analysis for the


searching methods.
About linear Search Methods:
Linear search, often known as sequential search, is the most basic search technique. In this type
of search, you go through the entire list and try to fetch a match for a single element. If you find
a match, then the address of the matching target element is returned.
On the other hand, if the element is not found, then it returns a NULL value.

Linear search analysis:


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.

Linear Search Algorithm:Linear Search ( Array A, Value x)

Linear Search ( Array Arr, Value a ) // Arr is the name of the array, and a is the searched
element.
Step 1: Set i to 0 // i is the index of an array which starts from 0
Step 2: ifi > n then go to step 7 // n is the number of elements in array
Step 3: if Arr[i] = a then go to step 6
Step 4: Set i to i + 1
Step 5: Goto step 2
Step 6: Print element a found at index i and go to step 8
Step 7: Print element not found
Step 8: Exit

Time complexity : O(n)

Example of Linear search:

Consider an array of size 7 with elements 13, 9, 21, 15, 39, 19, and 27 that starts with 0 and ends
with size minus one, 6.
Search element = 39

Step 1: The searched element 39 is compared to the first element of an array, which is 13.

BE-III (Semester V) IT 210450116021 16


Analysis and Design of Algorithms (3150703)

The match is not found, you now move on to the next element and try to implement a
comparison.
Step 2: Now, search element 39 is compared to the second element of an array, 9.

As both are not matching, you will continue the search.


Step 3: Now, search element 39 is compared with the third element, which is 21.

Again, both the elements are not matching, you move onto the next following element.
Step 4; Next, search element 39 is compared with the fourth element, which is 15.

As both are not matching, you move on to the next element.


Step 5: Next, search element 39 is compared with the fifth element 39.

A perfect match is found, you stop comparing any further elements and terminate the Linear
Search Algorithm and display the element found at location 4.

About Binary Search Methods:

Binary Search is a searching algorithm used in a sorted array by repeatedly dividing the search
interval in half. The idea of binary search is to use the information that the array is sorted and
reduce the time complexity to O(Log n).

BE-III (Semester V) IT 210450116021 17


Analysis and Design of Algorithms (3150703)

Algorithm:

 Begin with the mid element of the whole array as a search key.
 If the value of the search key is equal to the item then return an index of the search key.
 Or if the value of the search key is less than the item in the middle of the interval, narrow
the interval to the lower half.
 Otherwise, narrow it to the upper half.
 Repeatedly check from the second point until the value is found or the interval is empty.

Time complexity : O(log n)

Example:

Code:

/* Practical-6:Implement Linear searching and Binary searching. Do analysis for the searching
Methods */
//210450116021_KALP_PATEL

#include<stdio.h>

#include<sys/time.h>

int lsearch(int[],int);

int bsearch(int [],int,int,int);

int n;

BE-III (Semester V) IT 210450116021 18


Analysis and Design of Algorithms (3150703)

int main()

int a[50],i,s,beg,end,t1,t2,t3,t4;

printf("Enter the number of elements in Array: ");

scanf("%d",&n);

printf("Enter the values:");

for(i=0;i<n;i++)

scanf("%d",&a[i]);

beg=0;

end=n-1;

printf("Enter the element to search: ");

scanf("%d",&s);

struct timeval tt;

struct timezone tz;

gettimeofday(&tt,&tz);

t1=tt.tv_usec;

lsearch(a,s);

gettimeofday(&tt,&tz);

t2=tt.tv_usec;

printf("Time taken by Linear search is: %d\n",t2-t1);

gettimeofday(&tt,&tz);

t3=tt.tv_usec;

bsearch(a,s,beg,end);

BE-III (Semester V) IT 210450116021 19


Analysis and Design of Algorithms (3150703)

gettimeofday(&tt,&tz);

t4=tt.tv_usec;

printf("Time taken by Binary search is: %d\n",t4-t3);

int lsearch(int a[],int s)

int i;

for(i=0;i<n;i++)

if(s==a[i])

printf("\nUsing Linear Search\n");

printf("The element %d was found at index %d\n",s,i);

break;

if(i==n)

printf("The element %d is not present in the array",s);

return 0;

int bsearch(int a[],int s,int beg,int end)

int mid;

mid=(beg+end)/2;

if(s==a[mid])

BE-III (Semester V) IT 210450116021 20


Analysis and Design of Algorithms (3150703)

printf("\nUsing Binary Search\n");

printf("The element %d was found at index %d\n",s,mid);

else if(s<a[mid])

bsearch(a,s,beg,mid);

else if(s>a[mid])

bsearch(a,s,mid+1,end);

else

printf("The element %d is not present in the array",s);

BE-III (Semester V) IT 210450116021 21


Analysis and Design of Algorithms (3150703)

Input/Output:

BE-III (Semester V) IT 210450116021 22


Analysis and Design of Algorithms (3150703)

PRACTICAL – 7

Implement Merge sort with DAQ strategy


About Merge Sort: In Merge sort, we divide the array recursively in two halves, until each sub-
array contains a single element, and then we merge the sub-array in a way that it results into a
sorted array. merge() function merges two sorted sub-arrays into one, wherein it assumes that
array[l .. n] and arr[n+1 .. r] are sorted.

Merge sort is one of the efficient & fastest sorting algorithms with the following time complexity:
Time Complexity: O(n log n)

Algorithm:

MergeSort(arr[], l, r), where l is the index of the first element & r is the index of the last element.
If r > l
1. Find the middle index of the array to divide it in two halves:
m = (l+r)/2
2. Call MergeSort for first half:
mergeSort(array, l, m)
3. Call mergeSort for second half:
mergeSort(array, m+1, r)
4. Recursively, merge the two halves in a sorted manner, so that only one sorted array is left:
merge(array, l, m, r)

Example:
Array[ ]=85,24,63,45,17,31,96,50

1. Divide the unsorted array recursively until 1 element in each sub-array remains.

BE-III (Semester V) IT 210450116021 23


Analysis and Design of Algorithms (3150703)

2. Recursively, merge sub-arrays to produce sorted sub-arrays until all the sub-array merges and
only one array remains.

C Code:

//Practical-7: Implement Merge sort with DAQ strategy


//210450116021_KALP_PATEL

#include<stdio.h>
#include<conio.h>
void mergesort(int a[],int i,int j);
void merge(int a[],int i1,int j1,int i2,int j2);

int main()
{
int a[30],n,i;
printf("Enter no of elements:");
scanf("%d",&n);
printf("Enter array elements:");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
mergesort(a,0,n-1);
printf("\nSorted array is :");
for(i=0;i<n;i++)
printf("%d ",a[i]);
return 0;
}

void mergesort(int a[],int i,int j)

BE-III (Semester V) IT 210450116021 24


Analysis and Design of Algorithms (3150703)

{
int mid;
if(i<j)
{
mid=(i+j)/2;
mergesort(a,i,mid); //left recursion
mergesort(a,mid+1,j); //right recursion
merge(a,i,mid,mid+1,j); //merging of two sorted sub-arrays
}
}
void merge(int a[],int i1,int j1,int i2,int j2)
{
int temp[50]; //array used for merging
int i,j,k;
i=i1; //beginning of the first list
j=i2; //beginning of the second list
k=0;
while(i<=j1 && j<=j2) //while elements in both lists
{
if(a[i]<a[j])
temp[k++]=a[i++];
else
temp[k++]=a[j++];
}
while(i<=j1) //copy remaining elements of the first list
temp[k++]=a[i++];
while(j<=j2) //copy remaining elements of the second list
temp[k++]=a[j++];
//Transfer elements from temp[] back to a[]
for(i=i1,j=0;i<=j2;i++,j++)
a[i]=temp[j];
}

Input/Output:

BE-III (Semester V) IT 210450116021 25


Analysis and Design of Algorithms (3150703)

BE-III (Semester V) IT 210450116021 26


Analysis and Design of Algorithms (3150703)

PRACTICAL – 8

Implement Quick sort with DAQ strategy.


About Quick Sort: Like Merge Sort, QuickSort is a Divide and Conquer algorithm. It picks an
element as a pivot and partitions the given array around the picked pivot. There are many
different versions of quickSort that pick pivot in different ways.

Always pick the first element as a pivot.


Always pick the last element as a pivot (implemented below)
Pick a random element as a pivot.
Pick median as the pivot.
The key process in quickSort is a partition(). The target of partitions is, given an array and an
element x of an array as the pivot, put x at its correct position in a sorted array and put all smaller
elements (smaller than x) before x, and put all greater elements (greater than x) after x. All this
should be done in linear time.
Time complexity: O(n log n)

Algorithm:

Step 1 - Consider the first element of the list as pivot (i.e., Element at first position in the list).

Step 2 - Define two variables i and j. Set i and j to first and last elements of the list respectively.

Step 3 - Increment i until list[i] > pivot then stop.

Step 4 - Decrement j until list[j] < pivot then stop.

Step 5 - If i < j then exchange list[i] and list[j].

Step 6 - Repeat steps 3,4 & 5 until i > j.

Step 7 - Exchange the pivot element with list[j] element.

Example:

Array[ ]=5,3,8,1,4,6,2,7

BE-III (Semester V) IT 210450116021 27


Analysis and Design of Algorithms (3150703)

BE-III (Semester V) IT 210450116021 28


Analysis and Design of Algorithms (3150703)

C Code:

//Practical-8:Implement Quick sort with DAQ strategy


//210450116021_KALP_PATEL

#include<stdio.h>
#include<conio.h>
void quicksort(int a[],int low,int high)
{
int i, j, pivot, temp;
if(low<high)
{
pivot=low;
i=low;
j=high;
while(i<j)
{
while((a[i]<=a[pivot])&&(i<high))
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,low,j-1); // left subarray


quicksort(a,j+1,high); // right subarray
}
}
int main()
{
int i, n, a[10];
printf("Enter no. of element: ");
scanf("%d",&n);
printf("Enter %d integers\n", n);
for (i = 0; i < n; i++)
scanf("%d", &a[i]);
quicksort(a,0,n-1);
printf("Order of Sorted elements: ");
for(i=0;i<n;i++)

BE-III (Semester V) IT 210450116021 29


Analysis and Design of Algorithms (3150703)

printf(" %d",a[i]);
return 0;
}

Input/Output:

BE-III (Semester V) IT 210450116021 30


Analysis and Design of Algorithms (3150703)

PRACTICAL – 9

Implement Counting sort.


About 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 do some arithmetic to calculate the position of each object in the output sequence.

Characteristics of counting sort:


Counting sort makes assumptions about the data, for example, it assumes that values are going to
be in the range of 0 to 10 or 10 – 99 etc, Some other assumptions counting sort makes are input
data will be all real numbers.
Like other algorithms this sorting algorithm is not a comparison-based algorithm, it hashes the
value in a temporary count array and uses them for sorting.

Algorithm:

countingSort(array, n) // 'n' is the size of array


max = find maximum element in the given array
create count array with size maximum + 1
Initialize count array with all 0's
for i = 0 to n
find the count of every unique element and
store that count at ith position in the count array
for j = 1 to max
Now, find the cumulative sum and store it in count array
for i = n to 1
Restore the array elements
Decrease the count of every restored element by 1
end countingSort

Time Complexity: O(n+k) where n is the number of elements in the input array and k is the
range of input.

Example:
array are -

1. Find the maximum element from the given array. Let max be the maximum element.

BE-III (Semester V) IT 210450116021 31


Analysis and Design of Algorithms (3150703)

2. Now, initialize array of length max + 1 having all 0 elements. This array will be used to store
the count of the elements in the given array.

3. Now, we have to store the count of each array element at their corresponding index in the
count array.
The count of an element will be stored as - Suppose array element '4' is appeared two times, so
the count of element 4 is 2. Hence, 2 is stored at the 4th position of the count array. If any
element is not present in the array, place 0, i.e. suppose element '3' is not present in the array, so,
0 will be stored at 3rd position.

Now, store the cumulative sum of count array elements. It will help to place the elements at the
correct index of the sorted array.

Similarly, the cumulative count of the count array is -

4. Now, find the index of each element of the original array

BE-III (Semester V) IT 210450116021 32


Analysis and Design of Algorithms (3150703)

After placing element at its place, decrease its count by one. Before placing element 2, its count
was 2, but after placing it at its correct position, the new count for element 2 is 1.

Similarly, after sorting, the array elements are -

Now, the array is completely sorted.

BE-III (Semester V) IT 210450116021 33


Analysis and Design of Algorithms (3150703)

C Code:

//Program 9: Counting Sort


//210450116021_KALP_PATEL

#include<stdio.h>
#include<sys/time.h>
int c[10];
int main(){
int A[8]={2,1,0,4,1,1,5,4},k=5,t1,t2,i;
//display array
printf("\n Array is :\n");
for(i=0;i<=7;i++)
printf(" %d ",A[i]);
printf("\n");

struct timeval tt;


struct timezone tz;

gettimeofday(&tt,&tz);
t1=tt.tv_usec;//getting time t1

cs(A,k);//calling counting sort function

gettimeofday(&tt,&tz);
t2=tt.tv_usec;//getting time t2

printf("\n***************************");
printf("\n Time taken is %d. \n",t2-t1);
printf("***************************\n");
return 1;
}

int cs(int A[],int k){

int i,j,B[8];

//initialzing each elemnts of c to 0


for(i=0;i<=k;i++)
c[i]=0;

//frequencies of each
for(j=0;j<=7;j++)
c[A[j]]=c[A[j]]+1;

//Display frequency of each elemets


printf("\n Frequencies of each elemnts is:\n ");
for(i=0;i<=k;i++)
printf(" %d ",c[i]);
printf("\n");

BE-III (Semester V) IT 210450116021 34


Analysis and Design of Algorithms (3150703)

//cummulative freq
for(i=1;i<=k;i++)
c[i]=c[i]+c[i-1];

//display
printf("\nCummulative frequencies of each element is:\n");
for(i=0;i<=k;i++)
printf(" %d ",c[i]);
printf("\n");

//Arranging
for(j=7;j>=0;j--)
{
B[c[A[j]]-1]=A[j];
c[A[j]]=c[A[j]]-1;
}

//Display result:
printf("\n Sorted list is : \n");
for(i=0;i<=7;i++)
printf(" %d ",B[i]);
printf("\n");

Input/Output:

BE-III (Semester V) IT 210450116021 35

You might also like