Algorithms Review Report: Analysis of Algorithm
Algorithms Review Report: Analysis of Algorithm
Analysis of Algorithm
Algorithms Review Report
Student Information:
Sitara Shafiq 2017-CS-355
Report Submitted to:
Sir Samyan
[Type here]
2
Table of Content:
1. Sorting Algorithm
i) Selection Sort --------------------------------------------------------------3
ii) Heap Sort--------------------------------------------------------------------4
iii) Counting Sort---------------------------------------------------------------6
iv) Bucket Sort------------------------------------------------------------------19
v) Binary Insertion Sort------------------------------------------------------10
vi) Shell sort---------------------------------------------------------------------13
vii) Cycle Sort--------------------------------------------------------------------13
viii) Brick Sort----------------------------------------------------------------16
ix) Cartesian Sorting----------------------------------------------------------18
x) Radix Sort-------------------------------------------------------------------23
2. Searching Algorithm---------------------------------------------------------25
i) Fibonacci Search----------------------------------------------------------25
ii) Jump Search----------------------------------------------------------------27
iii) Interpolation Search------------------------------------------------------29
iv) Exponential Search--------------------------------------------------------31
v) Sublist Search---------------------------------------------------------------34
3. Divide and Conquer-----------------------------------------------------------34
i) Closest Pair of Point--------------------------------------------------------34
ii) FFT Algorithm----------------------------------------------------------------38
4. Dynamic Programming--------------------------------------------------------39
i) Friends pairing problem----------------------------------------------------39
ii) Tiling Problem-----------------------------------------------------------------40
[Type here]
3
Sorting Algorithm
i- Selection Sort:
Selection sort is a kind algorithm kinds an array through time and again
finding the minimum element from unsorted element and setting it at the start.
The algorithm continues sub arrays in a given array.
X) The sub array that's already looked after.
2) Remaining sub array that's unsorted.
In every generation of choice sort, the minimal detail (thinking about ascending
order) from the unsorted sub array is picked and moved to the looked after sub
array.
Time Complexity
Time complexity of Selection Sort is O(n2) because of two nested loops.
Pseudocode
procedure selection sort
list : array of items
n : size of list
for i = 1 to n - 1
/* set current element as minimum*/
min = i
for j = i+1 to n
if list[j] < list[min] then
min = j;
end if
end for
[Type here]
4
end for
end procedure
Time Complexity:
Overall time complexity of Heap Sort is O(nLogn).
#include <iostream>
int main()
[Type here]
6
{
int arr[] = {121, 10, 130, 57, 36, 17};
int n = sizeof(arr)/sizeof(arr[0]);
heapSort(arr, n);
Time Complexity:
O(n+k) where n is the number of elements in input array and k is the range of
input.
// C++ Program for counting sort
#include<bits/stdc++.h>
#include<string.h>
using namespace std;
#define RANGE 255
[Type here]
7
{
// The output character array
// that will have sorted arr
char output[strlen(arr)];
[Type here]
8
/*
For Stable algorithm
for (i = sizeof(arr)-1; i>=0; --i)
{
output[count[arr[i]]-1] = arr[i];
--count[arr[i]];
}
// Driver code
int main()
{
char arr[] = "geeksforgeeks";
[Type here]
9
countSort(arr);
[Type here]
10
#include <stdio.h>
if(item == a[mid])
return mid+1;
[Type here]
11
j = i - 1;
selected = a[i];
[Type here]
12
a[j+1] = a[j];
j--;
a[j+1] = selected;
int main()
int n = sizeof(a)/sizeof(a[0]), i;
insertionSort(a, n);
printf("%d ",a[i]);
[Type here]
13
return 0;
[Type here]
14
are located at accurate position, i.E., we don’t come again to cycle starting
point.
Time Complexity:
Time complexity of Cycle Sort is O(n2).
[Type here]
15
if (pos != cycle_start) {
swap(item, arr[pos]);
writes++;
}
[Type here]
16
while (!isSorted)
{
isSorted = true;
[Type here]
17
return;
}
oddEvenSort(arr, n);
printArray(arr, n);
return (0);
}
[Type here]
18
[Type here]
19
pQueue.pop();
if (popped_pair.second->left != NULL)
pQueue.push (make_pair(popped_pair.second->left-
>data,
popped_pair.second-
>left));
if (popped_pair.second->right != NULL)
pQueue.push (make_pair(popped_pair.second->right-
>data,
popped_pair.second->right));
}
return;
}
[Type here]
20
temp->data = arr[root];
temp->left = buildCartesianTreeUtil(leftchild[root],
arr, parent, leftchild, rightchild);
temp->right = buildCartesianTreeUtil(rightchild[root],
arr, parent, leftchild, rightchild);
return temp ;
}
// 'root' and 'last' stores the index of the root and the
// last processed of the Cartesian Tree.
// Initially we take root of the Cartesian Tree as the
// first element of the input array. This can change
// according to the algorithm
int root = 0, last;
[Type here]
21
// Just insert it
else if (rightchild[last] == -1)
{
rightchild[last] = i;
parent[i] = last;
leftchild[i] = -1;
}
// Reconfigure links
else
{
parent[rightchild[last]] = i;
leftchild[i] = rightchild[last];
[Type here]
22
rightchild[last]= i;
parent[i] = last;
}
5
\
[Type here]
23
10
\
28
/
30
/
40
*/
printSortedArr(arr, n);
return(0);
}
[Type here]
24
[Type here]
25
Searching Algorithm
Fibonacci Algorithm:
Let the searched element be x.
The idea is to first locate the smallest Fibonacci range that is extra than or equal
to the period of given array. Let the discovered Fibonacci variety be fib (m’th
Fibonacci range). We use (m-2)’th Fibonacci variety as the index (If it is a
legitimate index). Let (m-2)’th Fibonacci Number be I, we examine arr[i] with x, if
x is equal, we go back i. Else if x is more, we recur for subarray after i, else we
recur for subarray earlier than i.
Below is the entire algorithm
Let arr [0..N-1] be the input array and element to be searched be x.
1. Find the smallest Fibonacci Number extra than or identical to n. Let this
variety be fibM [m’th Fibonacci Number]. Let the 2 Fibonacci numbers preceding
[Type here]
26
or not it's fibMm1 [(m-1)’th Fibonacci Number] and fibMm2 [(m-2)’th Fibonacci
Number].
2. While the array has factors to be inspected:
1. Compare x with the closing detail of the range included by way of
fibMm2
2. If x suits, return index
3. Else If x is much less than the detail, circulate the three Fibonacci
variables two Fibonacci down, indicating removal of about rear -third of the
last array.
4. Else x is greater than the element, move the 3 Fibonacci variables
one Fibonacci down. Reset offset to index. Together those indicate removal
of approximately the front one-1/3 of the last array.
3. Since there might be a single element last for comparison, check if fibMm1
is 1. If Yes, examine x with that remaining detail. If in shape, return index.
int fib(int n)
{
if (n <= 1)
return n;
return fib(n-1) + fib(n-2);
}
int main ()
{
int n = 9;
cout << fib(n);
getchar();
return 0;
}
[Type here]
27
Jump Search:
Like Binary Search, Jump Search is a looking set of rules for looked after arrays.
The basic concept is to test fewer factors (than linear seek) via jumping ahead by
way of constant steps or skipping a few factors in place of looking all factors.
For example, assume we've an array arr[] of length n and block (to be jumped)
length m. Then we search at the indexes arr[0], arr[m], arr[2m]…..Arr[km] and so
forth. Once we discover the interval (arr[km] < x < arr[(k+1)m]), we carry out a
linear search operation from the index km to find the detail x.
Let’s don't forget the following array: (0, 1, 1, 2, three, five, eight, 13, 21, 34, 55,
89, one hundred forty four, 233, 377, 610). Length of the array is sixteen. Jump
seek will find the value of fifty five with the following steps assuming that the
block size to be jumped is four.
STEP 1: Jump from index zero to index 4;
STEP 2: Jump from index 4 to index eight;
STEP three: Jump from index eight to index 12;
STEP four: Since the detail at index 12 is more than 55 we are able to bounce back
a step to come to index eight.
STEP 5: Perform linear seek from index eight to get the detail fifty five.
// C++ program to implement Jump Search
#include <bits/stdc++.h>
using namespace std;
[Type here]
28
return -1;
[Type here]
29
Interpolation Search:
Given a looked after array of n uniformly dispensed values arr[], write a function
to look for a selected detail x inside the array.
Linear Search finds the element in O(n) time, Jump Search takes O(√ n) time and
Binary Search take O(Log n) time.
The Interpolation Search is an development over Binary Search for instances,
wherein the values in a sorted array are uniformly disbursed. Binary Search
usually goes to the center element to check. On the alternative hand,
interpolation search may match to one-of-a-kind locations in line with the fee of
the important thing being searched. For instance, if the value of the secret's
[Type here]
30
[Type here]
31
if (arr[pos] == x)
return pos;
// Driver Code
int main()
{
// Array of items on which search will
// be conducted.
int arr[] = {10, 12, 13, 16, 18, 19, 20, 21,
22, 23, 24, 33, 35, 42, 47};
int n = sizeof(arr)/sizeof(arr[0]);
Exponential Search:
The name of this searching set of rules may be deceptive because it works in
O(Log n) time. The call comes from the manner it searches an element.
[Type here]
32
The concept is to start with subarray size 1, examine its closing element with x,
then try size 2, then four and so on till last element of a subarray is not extra.
Once we find an index i (after repeated doubling of i), we recognise that the detail
have to be present between i/2 and i (Why i/2? Because we could not find a
greater cost in previous iteration)
Time Complexity:
O(log n)
// C++ program to find an element x in a
// sorted array using Exponential search.
#include <bits/stdc++.h>
using namespace std;
[Type here]
33
if (r >= l)
{
int mid = l + (r - l)/2;
// Driver code
int main(void)
{
int arr[] = {2, 3, 4, 10, 40};
int n = sizeof(arr)/ sizeof(arr[0]);
int x = 10;
int result = exponentialSearch(arr, n, x);
(result == -1)? printf("Element is not present in array")
: printf("Element is present at index %d",
result);
return 0;
}
[Type here]
34
#include <bits/stdc++.h>
using namespace std;
[Type here]
35
int x, y;
};
[Type here]
36
// Pick all points one by one and try the next points till the difference
// between y coordinates is smaller than d.
// This is a proven fact that this loop runs at most 6 times
for (int i = 0; i < size; ++i)
for (int j = i+1; j < size && (strip[j].y - strip[i].y) < min; ++j)
if (dist(strip[i],strip[j]) < min)
min = dist(strip[i], strip[j]);
[Type here]
37
return min;
}
[Type here]
38
// distance is strip[]
return min(d, stripClosest(strip, j, d) );
}
// Driver code
int main()
{
Point P[] = {{2, 3}, {12, 30}, {40, 50}, {5, 1}, {12, 10}, {3, 4}};
int n = sizeof(P) / sizeof(P[0]);
cout << "The smallest distance is " << closest(P, n);
return 0;
}
FFT Algorithm:
Cooley–Tukey Fast Fourier Transform (FFT) algorithm is the most not unusual set
of rules for FFT. It is a divide and conquer set of rules which goes in O(nlogn) time.
import numpy as np
def DFT_slow(x):
"""Compute the discrete Fourier Transform of the 1D array x"""
x = np.asarray(x, dtype=float)
N = x.shape[0]
n = np.arange(N)
k = n.reshape((N, 1))
M = np.exp(-2j * np.pi * k * n / N)
return np.dot(M, x)
[Type here]
39
5.DYNAMIC PROGRAMMING
or pair up.
for f(n - 1)
[Type here]
40
int countFriendsPairings(int n)
{
int dp[n + 1];
return dp[n];
}
// Driver code
int main()
{
int n = 4;
cout << countFriendsPairings(n) << endl;
return 0;
}
5.2 Tiling Problem
Given a “2 x n” board and tiles of size “2 x 1”, count the
number of ways to tile the given board using the 2 x 1 tiles. A tile can
either be placed horizontally i.e., as a 1 x 2 tile or vertically i.e., as 2 x
1 tile.
[Type here]
41
count(n) = n if n = 1 or n = 2
[Type here]