Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

DAA File1

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

Practical File

DESIGN AND ANALYSIS OF


ALGORITHM (PCIT 402)

Submitted to: Dr Monika

Submitted by: Gaurav Kumar

UE218039
EXPERIMENT-1
INTRODUCTION
Linear search- It is a type of algorithm for sequential searching of the
data. This algorithm finds a given element with O(n) complexity. It is
applied to a collection of items. Each and every item of the data is
searched sequentially, and returned if it matches the searched
element. If no matches are found, then the search keeps on
continuing till the end of the collected data. It is basically a
technique of exploring every element while traversing the list. The
searching algorithm can be applied to both the sorted and the
unsorted data. Practically linear search is rarely used because of the
faster searching options provided by other search algorithms like
binary search algorithms and hashtables.
Features of linear search algorithms

1. It is usually applied to a small list of unsorted or unordered data.


2. Time is linearly dependent on the number of elements, therefore
having a time complexity if O(n).
3. The implementation is very simple.

Binary search-Binary search is an efficient algorithm for finding an


element from a sorted list of elements. It is a searching
algorithm based on the design paradigm of divide and conquer. Itgives us
a pretty decent run time of O(log n) as compared to the O(n) of linear
search in worst-case scenarios. In this algorithm, we
recursively divide our array in half until we find the element we are
searching for or the list narrows down to one element which does not
match our element.

LIBRARY USED

1) < chrono>- <chrono> is a C++ header that provides a collection of types


and functions to work with time. It is a part of the C++ Standard Template
Library (STL) and it's included in C++11 and later versions. <chrono> provides
three main types of clocks: system_clock, steady_clock, and
high_resolution_clock.
These clocks are used to measure time in various ways :-
system_clock represents the system-wide real time wall clock. It’s affected by
the system’s time adjustments.
steady_clock represents a monotonically increasing clock that’s not affected by
changes to the system time.
high_resolution_clock is the clock with the shortest tick period available on the
system.

2) <iostream>- ostream stands for standard input-output stream. #include


iostream declares objects that control reading from and writing to the standard
streams. In other words, the iostream library is an object-oriented library that
provides input and output functionality using streams.

A stream is a sequence of bytes. You can think of it as an abstraction


representing a device. You can perform I/O operations on the device via this
abstraction. You must include iostream header file to input and output from a
C++ program.

LINEAR SEARCH CODE-

#include<iostream>
#include<chrono>
using namespace std;
int main()
{
auto start_time=chrono::system_clock::now();
int el,flag=0,i,s,n;
cout<<"Enter the size of array\n";
cin>>n;
int *arr=new int[n];
cout<<"enter the values in array "<<endl;
for(i=0;i<n;i++)
arr[i]=i;
cout<<"enter the number to be search in array "<<endl;
cin>>el;

for(i=0;i<10;i++)
{
if(arr[i]==el)
{
flag=1;
break;
}
else
continue;
}
auto end_time=chrono::system_clock::now();
if(flag==1)
{
cout<<"number is found "<<endl;
cout<<"and its value is "<<arr[i]<<endl;
cout<<"number found is the "<<s+1<<" element of the array "<<endl;
}
else
cout<<"number chosen is not from array ";
chrono::duration<double> elapsed_time= end_time-start_time;
cout<<"Elapsed time: "<<elapsed_time.count() <<"ms"<<"\n";
return 0;
}

Output-

Graph-
BINARY SEARCH CODE-

#include <iostream>
#include <chrono>
using namespace std;

int binary(int arr[], int r, int end, int beg)


{
int mid;
while(beg<=end){

mid = (beg + end) / 2;

if (arr[mid] == r)
{
// cout << arr[mid] << endl;
return 1;
break;
}
else if (arr[mid] < r)
{
beg = mid + 1;
}
else
{
end = mid - 1;
}
}

return -1;
};

int main()
{
int r;
int mid, end, beg;
beg = 0;
int arr[500000];
end = sizeof(arr)/sizeof(arr[0]);
for (int i = 0; i < 500000; i++)
{
arr[i] = i;
}
cout<<"enter the value you want to find: ";
cin >> r;

auto begin = chrono::high_resolution_clock::now();


int result = binary(arr, r, end - 1, beg);
if (result == 1)
cout << "element is found\n";
else
cout << "element is not found\n";

auto end1 = chrono::high_resolution_clock::now();


auto elapsed = chrono::duration_cast<chrono::nanoseconds>(end1 -
begin).count();
cout << elapsed;
}

Output-

Graph-
EXPERIMENT-2
Bubble sort - Bubble Sort is the simplest sorting algorithm that works
by repeatedly swapping the adjacent elements if they are in the
wrong order. This algorithm is not suitable for large data sets as its
average and worst-case time complexity is quite high.
Although it is simple to use, it is primarily used as an educational tool
because the performance of bubble sort is poor in the real world. It is
not suitablefor large data sets. The average and worst-case
complexity of Bubble sort is O(n2),where n is a number of items.

First Pass:
The largest element is placed in its correct position, i.e., the end of
the array.

Second Pass:
Place the second largest element at correct position
Third Pass:
Place the remaining two elements at their correct positions.

BUBBLE SORT CODE-


include<iostream>

include<chrono>

using namespace std;

int main()
{
auto begin= chrono:: high_resolution_clock::now();

int n;

cout<<"Enter the size of the array\n";


cin>>n;
int *arr=new int[n];

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

{
arr[n-1]=i;
}
int t;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
if(arr[j]<arr[j-1])
{
t=arr[j];

arr[j]=arr[j-1];

arr[j-1]=t;

}
}
}

auto end=chrono::high_resolution_clock::now();
auto elapsed= chrono::duration_cast<chrono::nanoseconds>(end-begin).count();

cout<<"elapsed time is:

"; cout<<elapsed;

return 0;
}

Output-
Enter the size of the array 10

elapsed time is:

1402400000 PS C:\c++>
Graph-
EXPERIMENT-3

Quick sort- QuickSort is a sorting algorithm based on the Divide and


Conquer algorithm that picks an element as a pivot and partitions the
given array around the picked pivot by placing the pivot in its correct
position in the sorted array.

How does Quick Sort work?


The key process in quick Sort is a partition(). The target of partitions
is to place the pivot (any element can be chosen to be a pivot) at it
correct position in the sorted array and put all smaller elements to
the left of the pivot, and all greater elements to the right of the pivot.

Partition is done recursively on each side of the pivot after the pivot
is placed in its correct position and this finally sorts the array.
Choice of Pivot:
There are many different choices for picking pivots.
1.Always pick the first element as a pivot.
2.Always pick the last element as a pivot (implemented below)
3.Pick a random element as a pivot.
4.Pick the middle as the pivot.

Partition Algorithm:
The logic is simple, we start from the leftmost element and keep
track of the index of smaller (or equal) elements as i. While
traversing, if we find a smaller element, we swap the current element
with arr[i]. Otherwise, we ignore the current element.

Time complexity:

○ Best Case Complexity - In Quicksoít, the best-case occuís when thepivot


element is the middle element oí neaí to the middle element. ľhe best-case
time complexity of quicksoít is O(n*logn).

○ Average Case Complexity - It occuís when the aííay elements aíe in


jumbled
oídeí that is not píopeíly ascending and not píopeíly descending. ľheaveíage
case time complexity of quicksoít is O(n*logn).

○ Worst Case Complexity - In quick soít, woíst case occuís when thepivot
element is eitheí gíeatest oí smallest element. Suppose, if the pivot element
is always the last element of the aííay, the woíst case would occuí when the
given aííay is soíted alíeady in ascending oí descending oídeí. ľhe woíst-
case time complexity of quicksoít is O(n2).
QUICK SORT CODE-

import time
import random
n = random.randint(20000001,20000001)

def in_array():

print("The length of array is:", n)


arr = []
for i in range(0,n-1):
a = random.randint(1,100)
arr.append(a)

#print("\nThe array formed is:", arr)


return arr

def quicksort(arr):
if len(arr) <= 1:
return arr
pivot = arr[0]
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
return quicksort(left) + middle + quicksort(right)

arr1 = in_array()

start_time = time.time()
#print("\nThe sorted array is: ",quicksort(arr1))
quicksort(arr1)
end_time = time.time()

print("\nThe time taken was: ", end_time - start_time)


Graph-
For starting element
as pivot:
For middle element as pivot:

For last element as pivot :

You might also like