You are on page 1of 19

Pawan (19-811) 1

PRACTICAL FILE

ME (IT) 1st Semester

ADVANCED ANALYSIS ALGORITHM


July, 2019 – December, 2019

Submitted By
PAWAN KUMAR
Roll Number:
19-811

Submitted To
Dr. Mandeep kaur

Information and Technology


University Institute of Engineering and Technology
Panjab University, Chandigarh – 160014, INDIA
2019
Pawan (19-811) 2

INDEX
S.
No. Name of Practical/Program Page no
* Introduction to Algorithm 3-6

1 Write a python program for merge sort and analyse the run 7-9
time and no of function calls for different input

2 Write a python program for quick sort and analyse the run 10-12
time and no of function calls for different input

3 Write a python program for Linear Search and analyse best 13-14
case , worst case and average case run time for different
input

4 Write an efficient program to find the sum of contiguous 15


subarray within a one-dimensional array of no’s which has
the largest sum.

5 Find the maximum no in O(n) time and O(1) extra space in 16


1D array

6 Given an array of integers , count no of subarrays (of size 17


more than one) that are strictly increasing
Expected Time complexity : O(n)
Expected Extra space : O(1)

8 Given a sorted array (sorted in non-decreasing order) of 18-19


positive numbers, find the smallest positive integer value
that cannot be represented as sum of elements of any subset
of given set.
Expected Time complexity: O(n)
Pawan (19-811) 3

Expected Extra Space: O(1)

INTRODUCTION TO ALGORITHM

An algorithm is a procedure or formula for solving a problem,


based on conducting a sequence of specified actions. A
computer program can be viewed as an elaborate algorithm. In
mathematics and computer science, an algorithm usually means
a small procedure that solves a recurrent problem.
Algorithms are widely used throughout all areas of IT
(information technology). A search engine algorithm, for
example, takes search strings of keywords and operators as
input, searches its associated database for relevant web pages,
and returns result.
An encryption algorithm transforms data according to specified
actions to protect it.
Algorithms can be expressed in many kinds of notation,
including natural language, pseudocode, flowcharts, drakon-
charts, programming languages or control tables. Natural
language expressions of algorithms tend to be verbose and
ambiguous, and are rarely used for complex or technical
algorithms. Pseudocode, flowcharts, drakon-charts and control
tables are structured ways to express algorithms that avoid many
of the ambiguities common in natural language statements.
Programming languages are primarily intended for expressing
algorithms in a form that can be executed by a computer, but are
often used as a way to define or document algorithms.
Pawan (19-811) 4

Characteristics of Algorithm

● Precision – the steps are precisely stated(defined).


● Uniqueness – results of each step are uniquely defined and
only depend on the input and the result of the preceding steps.
● Finiteness – the algorithm stops after a finite number of
instructions are executed.
● Generality – the algorithm applies to a set of inputs.
● Input-An algorithm should have 0 or more well-defined
inputs.
● Output-An algorithm should have 1 or more well-defined
outputs, and should match the desired output.

Asymptotic Notation

Usually, the time required by an algorithm falls under three types –


● Best Case − Minimum time required for program execution.
● Average Case − Average time required for program execution.
● Worst Case − Maximum time required for program execution.
Following are the commonly used asymptotic notations to calculate the
running time complexity of an algorithm.
● Ο Notation
● Ω Notation
● θ Notation
Big Oh Notation, Ο
The notation Ο(n) is the formal way to express the upper bound of an
algorithm's running time. It measures the worst case time complexity or
the longest amount of time an algorithm can possibly take to complete.
f(n)<=c*g(n)
Pawan (19-811) 5

Big-Omega Notation, Ω
The notation Ω(n) is the formal way to express the lower bound of an
algorithm's running time. It measures the best case time complexity or the
best amount of time an algorithm can possibly take to complete.
f(n)>=c*g(n)

Theta Notation, θ
The notation θ(n) is the formal way to express both the lower bound and
the upper bound of an algorithm's running time. It is represented as
follows −
Pawan (19-811) 6

Small-o
Small-o, commonly written as o, is an Asymptotic Notation to denote the
upper bound (that is not asymptotically tight) on the growth rate of
runtime of an algorithm.
f(n) is o(g(n)), if for any real constant c (c > 0), f(n) is < c g(n) for every
input size n (n > 0).
The definitions of O-notation and o-notation are similar. The main
difference is that in f(n) = O(g(n)), the bound f(n) <= g(n) holds for some
constant c > 0, but in f(n) = o(g(n)), the bound f(n) < c g(n) holds for all
constants c > 0.

Small-omega
Small-omega, commonly written as ω, is an Asymptotic Notation to
denote the lower bound (that is not asymptotically tight) on the growth
rate of runtime of an algorithm.
f(n) is ω(g(n)), if for any real constant c (c > 0), f(n) is > c g(n) for every
input size n (n > 0).
The definitions of Ω-notation and ω-notation are similar. The main
difference is that in f(n) = Ω(g(n)), the bound f(n) >= g(n) holds for some
constant c > 0, but in f(n) = ω(g(n)), the bound f(n) > c g(n) holds for all
constants c > 0.
Pawan (19-811) 7

1) Write a python program for merge sort and


analyse the run time and no of function calls for
different input

Code:

import random
import time

Start = 1
Stop = 8
limit = 4

R = random.sample(range(Start, Stop), limit)


print("The nos are :", R)

start_time = time.time()
def mergeSort(R):
mergeSort.counter +=1

if len(R)>1:
mid = len(R)//2
lefthalf = R[:mid]
righthalf = R[mid:]

#recursion
mergeSort(lefthalf)
mergeSort(righthalf)

i=0
j=0
k=0

while i < len(lefthalf) and j < len(righthalf):


Pawan (19-811) 8

if lefthalf[i] < righthalf[j]:


R[k]=lefthalf[i]
i=i+1
else:
R[k]=righthalf[j]
j=j+1
k=k+1

while i < len(lefthalf):


R[k]=lefthalf[i]
i=i+1
k=k+1

while j < len(righthalf):


R[k]=righthalf[j]
j=j+1
k=k+1
mergeSort.counter=0

mergeSort(R)
print("\nthe sorted nos :",R)
print("time taken %s seconds ---" % (time.time() - start_time))

f= open("merge.txt","a")
f.write("\n No of inputs : %s " %limit)
f.write(" \nTime taken : %s seconds ---\n" % (time.time() -
start_time))
f.write(" Funcation calls : %s" %mergeSort.counter)
f.write(" \
n-----------------------------------------------------------------------------------
--------------------------------------------------------------\n")
f.close()

# start = time.clock()
#end = time.clock()
#times.append(end-start)
Pawan (19-811) 9

Output:
Pawan (19-811) 10

2) Write a python program for quick sort and


analyse the run time and no of function calls for
different input

Code :
import random

import time

Start = 1

Stop = 2000000

limit = 1000000

R = random.sample(range(Start, Stop), limit)

print("The nos are :", R)

start_time = time.time()

def quicksort(R, start, end):

'''Sorts the list from indexes start to end - 1 inclusive.'''

quicksort.counter +=1

if end - start > 1:

p = partition(R, start, end)

quicksort(R, start, p)

quicksort(R, p + 1, end)
Pawan (19-811) 11

def partition(R, start, end):

pivot = R[start]

i = start + 1

j = end - 1

while True:

while (i <= j and R[i] <= pivot):

i=i+1

while (i <= j and R[j] >= pivot):

j=j-1

if i <= j:

R[i], R[j] = R[j], R[i]

else:

R[start], R[j] = R[j], R[start]

return j

quicksort.counter =0

alist = [int(x) for x in R]

quicksort(R, 0, len(R))

print('Sorted list: ', end='')

print(R)

print("time taken %s seconds ---" % (time.time() - start_time))

f= open("quick.txt","a")

f.write("\n No of inputs : %s " %limit)


Pawan (19-811) 12

f.write(" \nTime taken : %s seconds ---\n" % (time.time() - start_time))

f.write(" Funcation calls : %s" %quicksort.counter)

f.write(" \
n----------------------------------------------------------------------------------------------------------
---------------------------------------\n")

f.close()

# start = time.clock()

#end = time.clock()

#times.append(end-start)

Output:
Pawan (19-811) 13

3) Write a python program for Linear Search and


analyse best case , worst case and average case
run time for different input

Code:

print("Enter your number:")


x = input()
y = int(x)
arr = []
import random
for i in range(y):
a = random.randrange(1, 200)
arr.append(a)
import time
start_time = time.time()
def search(arr, c):
for i in range(len(arr)):
if arr[i] == c:
return i
break
return -1
print("Best case time:")
c = arr[0]
q=search(arr,c)
print(time.time() - start_time)
print("Average case time:")
n=len(arr)
c = arr[int((n-1)/2)]
z=search(arr,c)
print(time.time() - start_time)
Pawan (19-811) 14

print("Worst case time:")


n=len(arr)
z=search(arr,0)
print(time.time() - start_time)
print("What you want to find:")
l = input()
c = int(l)
p=search(arr, c)
if p==-1:
print("not found")
else:
print("Position of "+"%s" %c +" is: " "%s" %p)

Output:
Pawan (19-811) 15

4) Write an efficient program to find the sum of


contiguous subarray within a one-dimensional
array of no’s which has the largest sum.

Code :

def maxSubArraySum(a,size):

max_so_far = 0
max_ending_here = 0

for i in range(0, size):


max_ending_here = max_ending_here + a[i]
if max_ending_here < 0:
max_ending_here = 0
elif (max_so_far < max_ending_here):
max_so_far = max_ending_here

return max_so_far
a = [-2, -3, 4, -1, -2, 1, 5, -3]
print("Maximum contiguous sum is" , maxSubArraySum(a,len(a)))

Output:
Pawan (19-811) 16

5) Find the maximum no in O(n) time and O(1)


extra space in 1D array

Code :

def maxRepeating(arr, n, k):

for i in range(0, n):


arr[arr[i]%k] += k

max = arr[0]
result = 0
for i in range(1, n):

if arr[i] > max:


max = arr[i]
result = i

return result

arr = [2, 3, 3, 5, 3, 4, 1, 7]
n = len(arr)
k=8
print("The maximum repeating number is",maxRepeating(arr, n, k))

Output:
Pawan (19-811) 17

6) Given an array of integers , count no of


subarrays (of size more than one) that are
strictly increasing
Expected Time complexity : O(n)
Expected Extra space : O(1)

Code :

def countIncreasing(arr, n):

cnt = 0

for i in range(0, n) :

for j in range(i + 1, n) :
if arr[j] > arr[j - 1] :
cnt += 1

break
return cnt

arr = [1, 2, 2, 4]
n = len(arr)
print ("Count of strictly increasing subarrays is",
countIncreasing(arr, n))

Output:
Pawan (19-811) 18

8) Given a sorted array (sorted in non-decreasing


order) of positive numbers, find the smallest
positive integer value that cannot be
represented as sum of elements of any subset
of given set.
Expected Time complexity: O(n)
Expected Extra Space: O(1)

Code:
def findSmallest(arr, n):

res = 1

for i in range (0, n ):

if arr[i] <= res:

res = res + arr[i]

else:

break

return res

arr1 = [1, 3, 4, 5]

n1 = len(arr1)

print(findSmallest(arr1, n1))

arr2= [1, 2, 6, 10, 11, 15]


Pawan (19-811) 19

n2 = len(arr2)

print(findSmallest(arr2, n2))

arr3= [1, 1, 1, 1]

n3 = len(arr3)

print(findSmallest(arr3, n3))

arr4 = [1, 1, 3, 4]

n4 = len(arr4)

print(findSmallest(arr4, n4))

Output:

You might also like