Professional Documents
Culture Documents
KALP
KALP
PRACTICAL – 1
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
(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
(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
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]);
}
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;
}
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++)
{
printf(" %d ",a[j]); //Printing the sorted elements
}
printf("\n");
return 1;
}
Input/Output:
PRACTICAL – 2
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
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
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.
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 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:
PRACTICAL – 3
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
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++)
{
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:
PRACTICAL – 4
/* 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;
}
Input/Output:
PRACTICAL – 5
Algorithm:
Example:
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:
PRACTICAL – 6
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
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.
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.
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.
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.
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).
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.
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 n;
int main()
int a[50],i,s,beg,end,t1,t2,t3,t4;
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
beg=0;
end=n-1;
scanf("%d",&s);
gettimeofday(&tt,&tz);
t1=tt.tv_usec;
lsearch(a,s);
gettimeofday(&tt,&tz);
t2=tt.tv_usec;
gettimeofday(&tt,&tz);
t3=tt.tv_usec;
bsearch(a,s,beg,end);
gettimeofday(&tt,&tz);
t4=tt.tv_usec;
int i;
for(i=0;i<n;i++)
if(s==a[i])
break;
if(i==n)
return 0;
int mid;
mid=(beg+end)/2;
if(s==a[mid])
else if(s<a[mid])
bsearch(a,s,beg,mid);
else if(s>a[mid])
bsearch(a,s,mid+1,end);
else
Input/Output:
PRACTICAL – 7
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.
2. Recursively, merge sub-arrays to produce sorted sub-arrays until all the sub-array merges and
only one array remains.
C Code:
#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;
}
{
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:
PRACTICAL – 8
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.
Example:
Array[ ]=5,3,8,1,4,6,2,7
C Code:
#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;
printf(" %d",a[i]);
return 0;
}
Input/Output:
PRACTICAL – 9
Algorithm:
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.
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.
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.
C Code:
#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");
gettimeofday(&tt,&tz);
t1=tt.tv_usec;//getting time t1
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 i,j,B[8];
//frequencies of each
for(j=0;j<=7;j++)
c[A[j]]=c[A[j]]+1;
//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: