Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (1 vote)
220 views

Algorithm Design and Analysis GGSIPU Complete Lab File

The heap sort algorithm sorts an array by using a binary heap data structure. It first builds a max heap from the input array. It then repeatedly swaps the first element of the array (which is the largest) with the last non-sorted element and calls heapify to rearrange the reduced heap. This process is repeated until the whole array is sorted. The time complexity of heap sort is O(n log n) as building the max heap takes O(n) time and each swap operation takes O(log n) time.

Uploaded by

Ashwini Anand
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (1 vote)
220 views

Algorithm Design and Analysis GGSIPU Complete Lab File

The heap sort algorithm sorts an array by using a binary heap data structure. It first builds a max heap from the input array. It then repeatedly swaps the first element of the array (which is the largest) with the last non-sorted element and calls heapify to rearrange the reduced heap. This process is repeated until the whole array is sorted. The time complexity of heap sort is O(n log n) as building the max heap takes O(n) time and each swap operation takes O(log n) time.

Uploaded by

Ashwini Anand
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

Netaji Subhas University Of Technology East Campus

(formerly Ambedkar Institute Of Advanced Communication Technologies and Research)


Govt. Of NCT of Delhi

ALGORITHMS ANALYSIS AND DESIGN LAB

(ETCS-351)

Faculty Inc. – Prof. AUDITHAN SIVARAMAN

Submitted By :-
NAME :- Ashwini Anand Ojha
Enroll. No. :- 03310102719
BATCH :- B.Tech(Computer Science and Engineering), 2019-23
SEMESTER :- 5th
Serial No. Experiment Page No. Faculty
Sign.
To implement selection
1. sort algorithm using an
1-2
array as a data structure.

To implement bubble
2. sort algorithm using an
3-4
array as a data structure.

To implement merge sort


3. algorithm using an array
5-8
as a data structure.

To implement quick sort


4. algorithm using an array
9-11
as a data structure.

To implement heap sort


5. algorithm using an array
12-14
as a data structure.

To implement Linear
6. search and Binary search
15-17
algorithms.

To implement Rabin-Karp
7. Algorithm for Pattern
18-20
Searching.

To implement Knuth,
8. Morris, and Pratt string
21-23
searching algorithm.
EXPERIMENT - 1
AIM : To implement selection sort algorithm using an array as a data structure.

THEORY :
The selection sort algorithm sorts an array by repeatedly finding the minimum element
(considering ascending order) from the unsorted part and putting it at the beginning.
The algorithm maintains two subarrays in a given array :
1) The subarray which is already sorted.
2) Remaining subarray which is unsorted.
In every iteration of selection sort, the minimum element (considering ascending order)
from the unsorted subarray is picked and moved to the sorted subarray.

CODE :

#include <stdio.h>
int main()
{
int a[100], n, i, j, position, swap;
printf("Enter number of elements");
scanf("%d", &n);
printf("Enter %d Numbers", n);
for (i = 0; i < n; i++)
scanf("%d", &a[i]);
for(i = 0; i < n - 1; i++)
{
position=i;
for(j = i + 1; j < n; j++)
{
if(a[position] > a[j])
position=j;
}
if(position != i)
{
swap=a[i];
a[i]=a[position];
a[position]=swap;
}
}
printf("Sorted Array:n");
for(i = 0; i < n; i++)
printf("%d", a[i]);
return 0;
}

OUTPUT
EXPERIMENT - 2

AIM : To implement bubble sort algorithm using an array as a data structure.

THEORY :
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the
adjacent elements if they are in the wrong order.

CODE :

int main()
{
int array[100], n, i, j, swap;
printf("Enter number of elements\n");
scanf("%d", &n);
printf("Enter %d Numbers:n", n);

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


scanf("%d", &array[i]);

for(i = 0 ; i < n - 1; i++)


{
for(j = 0 ; j < n-i-1; j++)
{
if(array[j] > array[j+1])
{
swap=array[j];
array[j]=array[j+1];
array[j+1]=swap;
}
}
}

printf("Sorted Array:n");

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


printf("%d", array[i]);

return 0;
}
OUTPUT
EXPERIMENT - 3
AIM : To implement merge sort algorithm using an array as a data structure.

THEORY :
Merge Sort is a Divide and Conquer algorithm. It divides the input array into two halves,
calls itself for the two halves, and then merges the two sorted halves. The merge()
function is used for merging two halves. The merge(arr, l, m, r) is a key process that
assumes that arr[l..m] and arr[m+1..r] are sorted and merges the two sorted subarrays
into one.

CODE :

#include <stdio.h>
#include <stdlib.h>

// Merges two subarrays of arr[].

// First subarray is arr[l..m]

// Second subarray is
arr[m+1..r]

void merge(int arr[], int l,


int m, int r)
{
int i, j, k;
int n1 = m - l
+ 1; int n2 = r
- m;

/* create temp arrays */


int L[n1], R[n2];

/* Copy data to temp arrays L[] and R[] */


for (i = 0; i < n1; i++)
L[i] = arr[l + i];
for (j = 0; j < n2; j++)
R[j] = arr[m + 1 + j];
/* Merge the temp arrays back into
arr[l..r]*/ i = 0; // Initial index of
first subarray
j = 0; // Initial index of second subarray
k = l; // Initial index of merged subarray
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
}
else {
arr[k] = R[j];
j++;
}
k++;
}

/* Copy the remaining elements of L[], if there


are any */
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}

/* Copy the remaining elements of R[], if there


are any */
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}
/* l is for left index and r is right
index of the sub-array of arr to be
sorted */ void mergeSort(int arr[],
int l, int r)
{
if (l < r) {
// Same as (l+r)/2, but avoids overflow for
// large l and h
int m = l + (r - l) / 2;

// Sort first and


second halves
mergeSort(arr, l, m);
mergeSort(arr, m + 1, r);

merge(arr, l, m, r);
}
}

/* UTILITY FUNCTIONS */
/* Function to print an array */
void printArray(int A[], int size)
{
int i;
for (i = 0; i < size; i++)
printf("%d ", A[i]);
printf("\n");
}
/* Driver code */
int main()
{
int arr[] = { 12, 11, 13, 5, 6, 7 };
int arr_size = sizeof(arr) / sizeof(arr[0]);

printf("Given array is \n");


printArray(arr, arr_size);

mergeSort(arr, 0, arr_size - 1);

printf("\nSorted array is \n");


printArray(arr, arr_size);
return 0;
}
OUTPUT
EXPERIMENT - 4
AIM : To implement quick sort algorithm using an array as a data structure.

THEORY :
QuickSort is a Divide and Conquer algorithm. It picks an element as pivot and
partitions the given array around the picked pivot.
The key process in quickSort is partition(). Target of partitions is, given an array and an
element x of array as pivot, put x at its correct position in sorted array and put all smaller
elements (smaller than x) before x, and put all greater elements (greater than x) after x.

CODE :
#include <stdio.h>

void quicksort (int [], int, int);

int main()
{
int list[50];
int size, i;

printf("Enter the number of elements: ");


scanf("%d", &size);
printf("Enter the elements to be
sorted:\n"); for (i = 0; i < size;
i++) {

scanf("%d", &list[i]);
}
quicksort(list, 0, size - 1);
printf("After applying quick sort\n");
for (i = 0; i < size; i++)
{
printf("%d ", list[i]);
}
printf("\n");

return 0;
}

void quicksort(int list[], int low, int high)


{
int pivot, i, j, temp;
if (low < high)
{
pivot = low;
i = low;
j = high;
while (i < j)
{
while (list[i] <= list[pivot] && i <= high)
{
i++;
}
while (list[j] > list[pivot] && j >= low)
{
j--;
}
if (i < j)
{
temp = list[i];
list[i] = list[j];
list[j] = temp;
}
}
temp = list[j];
list[j] = list[pivot];
list[pivot] = temp;
quicksort(list, low, j - 1);
quicksort(list, j + 1, high);
}
}
OUTPUT
EXPERIMENT - 5
AIM : To implement heap sort algorithm using an array as a data structure.

THEORY :
Heap sort is a comparison-based sorting technique based on Binary Heap data structure.
It is similar to selection sort where we first find the minimum element and place the
minimum element at the beginning. We repeat the same process for the remaining
elements.

CODE :

#include <stdio.h>

// Function to swap the the position of two


elements void swap(int *a, int *b) {
int temp =
*a; *a =
*b;
*b = temp;
}

void heapify(int arr[], int n, int i) {


// Find largest among root, left child
and right child int largest = i;
int left = 2 * i
+ 1; int right =
2 * i + 2;

if (left < n && arr[left] > arr[largest])


largest = left;

if (right < n && arr[right] > arr[largest])


largest = right;

// Swap and continue heapifying if root is


not largest if (largest != i) {
swap(&arr[i],
&arr[largest]);
heapify(arr, n,
largest);
}
}
// Main function to do
heap sort void
heapSort(int arr[], int n)
{
// Build max heap
for (int i = n / 2 - 1; i >= 0; i--)
heapify(arr, n, i);

// Heap sort
for (int i = n - 1; i >= 0; i--) {
swap(&arr[0], &arr[i]);

// Heapify root element to get highest element


at root again heapify(arr, i, 0);
}
}

// Print an array
void printArray(int arr[], int n) {
for (int i = 0; i < n; ++i)
printf("%d ", arr[i]);
printf("\n");
}

// Driver
code int
main() {
int arr[] = {1, 12, 9, 5, 6, 10};
int n = sizeof(arr) / sizeof(arr[0]);

heapSort(arr, n);

printf("Sorted array is \n");


printArray(arr, n);
}
OUTPUT
EXPERIMENT - 6
AIM : To implement Linear search and Binary search algorithms.

THEORY :

Linear Search :
Iterate through every element in an array, check if it matches with the given element.

Binary Search :
Search a sorted array by repeatedly dividing the search interval in half. Begin with an interval
covering the whole array. 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 until the value is found or the interval is empty.

CODE :

1. Linear Search :

#include<stdio.h>

int main()
{
int a[20],i,x,n;
printf("How many elements?");
scanf("%d",&n);

printf("Enter array elements:n");


for(i=0;i<n;++i)
scanf("%d",&a[i]);

printf("nEnter element to search:");


scanf("%d",&x);

for(i=0;i<n;++i)
if(a[i]==x)
break;

if(i<n)
printf("Element found at index %d",i);
else
printf("Element not found");

return 0;
}
OUTPUT :

2. Binary Search :

#include <stdio.h>

int binarySearch(int array[], int x, int low, int high) {

while (low <= high) {


int mid = low + (high - low) / 2;

if (array[mid] == x)
return mid;

if (array[mid] < x)
low = mid + 1;

else
high = mid - 1;
}

return -1;
}
OUTPUT :
EXPERIMENT - 7
AIM : To implement Rabin-Karp Algorithm for Pattern Searching

THEORY :
Rabin-Karp algorithm is an algorithm used for searching/matching patterns in the text using
a hash function. Unlike Naive string matching algorithm, it does not travel through every
character in the initial phase rather it filters the characters that do not match and then
performs the comparison.

CODE :

#include<stdio.h>
#include<string.h>

// d is the number of characters in the


input alphabet #define d 256

void search(char pat[], char txt[], int q)


{
int M = strlen(pat);
int N = strlen(txt);
int i, j;
int p = 0; // hash value for pattern
int t = 0; // hash value for txt
int h = 1;

// The value of h would be "pow(d,


M-1)%q" for (i = 0; i < M-1; i++)
h = (h*d)%q;

// Calculate the hash value of pattern and first


// window of text
for (i = 0; i < M; i++)
{
p = (d*p + pat[i])%q;
t = (d*t + txt[i])%q;
}
// Slide the pattern over text
one by one for (i = 0; i <= N -
M; i++)
{

// Check the hash values of current window of text


// and pattern. If the hash values match then only
// check for characters on by one
if ( p == t )
{
/* Check for characters one by one */
for (j = 0; j < M; j++)
{
if (txt[i+j] != pat[j])
break;
}

// if p == t and pat[0...M-1] =
txt[i, i+1, ...i+M-1] if (j == M)
printf("Pattern found at index %d \n", i);
}

// Calculate hash value for next window of text: Remove


// leading digit, add trailing digit
if ( i < N-M )
{
t = (d*(t - txt[i]*h) + txt[i+M])%q;

// We might get negative value of t, converting it


// to positive
if (t < 0)
t = (t + q);
}
}
}
/* Driver Code */
int main()
{
char txt[] = "CREKS FOR MECKS";
char pat[] = "CREK";

// A prime
number int q =
101;

// function call
search(pat,
txt, q);
return 0;
}

OUTPUT
EXPERIMENT - 8
AIM : To implement Knuth, Morris, and Pratt string searching algorithm.

THEORY :
The KMP Algorithm (or Knuth, Morris, and Pratt string searching algorithm) cleverly uses
the previous comparison data. It can search for a pattern in O(n) time as it never re-
compares a text symbol that has matched a pattern symbol. However, it uses a partial
match table to analyze the pattern structure. Construction of a partial match table takes
O(m) time. Therefore, the overall time complexity of the KMP algorithm is O(m + n).

CODE :
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

// Function to implement the KMP algorithm


void KMP(const char* text, const char* pattern, int m, int n)
{
// base case 1: pattern is NULL
or empty if (*pattern == '\0' ||
n == 0) {
printf("The pattern occurs with shift 0");
}

// base case 2: text is NULL, or text's length is less


than that of pattern's if (*text == '\0' || n > m) {
printf("Pattern not found");
}

// next[i] stores the index of the next best partial match


int next[n + 1];

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


next[i] = 0;
}
for (int i = 1; i < n; i++)
{
int j = next[i + 1];

while (j > 0 && pattern[j] != pattern[i]) {


j = next[j];
}

if (j > 0 || pattern[j] == pattern[i]) {


next[i + 1] = j + 1;
}
}

for (int i = 0, j = 0; i < m; i++)


{
if (*(text + i) == *(pattern + j))
{
if (++j == n) {
printf("The pattern occurs with shift %d\n", i - j + 1);
}
}
else if (j > 0)
{
j = next[j];
i--; // since `i` will be incremented in the next iteration
}
}
}

// Program to implement the KMP


algorithm in C int main(void)
{
char* text =
"ABCABAABCABAC"; char*
pattern = "CAB";

int n = strlen(text);
int m = strlen(pattern);

KMP(text, pattern, n, m);

return 0;
}
OUTPUT

You might also like