You are on page 1of 5

Department of CSE NIT ROURKELA

CS 6381: Advanced Programming Laboratory Test –I, 2021


Maximum Time allowed: 1hour, upload to MS Team on or before 11.45AM

Mail your report [Source Codes + Simulation results +Observations] as a single


file with name as Roll NoTEST2021.

Binary insertion sort employs a binary search to determine the correct location to
insert new elements, and therefore performs ⌈log 2(n)⌉ comparisons in the worst
case, which is O(n log n). The algorithm as a whole still has a running time of O(n2)
on average because of the series of swaps required for each insertion. The
number of swaps can be reduced by calculating the position of multiple elements
before moving them. For example, if the target position of two elements is
calculated before they are moved into the right position, the number of swaps
can be reduced by about 25% for random data. Write a program to simulate
performance of BINARY INSERTION SORT and report the findings graphically with
your observations.

Furthr modification

Here take the element and if element is greater than the previous element store it in
temp variable and find the location of the element , store both information and again
start iteration without swapping and if element is greater then the pervious store it untill
the element come to be greatrer then the previous elemnt in array , after this go in
while loop and start swapping and put the element in their correct position with all the
elements .
Department of CSE NIT ROURKELA
CS 6381: Advanced Programming Laboratory Test –I, 2021

clear all

a=round(rand(1,100)*100);

n=100;

a2=a

nelt=zeros(1,n)

modcomp=zeros(1,n)

iscomp=zeros(1,n)

k=1

for i = 1:n

nelt(k)=i

[a,comp]=modified_isForis_bs(a,n);

modcomp(k)=comp

[comp2]=is(a2,n)

iscomp(k)=comp2

k=k+1

end

plot(nelt,comp,nelt,comp2)
Department of CSE NIT ROURKELA
CS 6381: Advanced Programming Laboratory Test –I, 2021

function [a,comp] = modified_isForis_bs(a,n)

comp=0;

for i=1:n

key= a(i)

j=i-1

[a,loc]=binarysearchrec(a,1,j,key)

while j >= loc

comp = comp +1

a(j+1)= a(j)

j = j-1

end

a(j+1) = key

end

end

function [arr,mid] = binarysearchrec(arr,left,right,key)

if right<=left
Department of CSE NIT ROURKELA
CS 6381: Advanced Programming Laboratory Test –I, 2021
if key>arr(left)

mid = left+1

return

else

mid=left

return

end

end

mid = left + (right - left)//2

if arr(mid)==key

return mid+1

elseif arr(mid) > key

[arr,mid] =binarysearch_it(arr,left,mid-1,key)

else

[arr, mid]= binarysearch_it(arr,mid+1,right,key)

end

End

function [comp] = is(a,n)

comp=0;

for i=1:n

key= a(i);

j=i-1;
Department of CSE NIT ROURKELA
CS 6381: Advanced Programming Laboratory Test –I, 2021

while j>0 && a(j)>key

comp = comp +1;

a(j+1)= a(j);

j = j-1;

end

a(j+1) = key;

end

End

Here in this it will find the correct position where the element should be placed by using binary
seach and placed it by swapping in insertion sort .

You might also like