Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 18

Practical File

Of
Design of Algorithms and Analysis
for
B.Tech.(CSE) degree program
Submitted by
Abidullah
Roll No.17002101
CSE 6th Semester

Submitted to
Ms. Astha Gautam
Associate Professor
Department of CSE
APG (Alakh Prakash Goyal) Shimla University

Date: 22/06/2020
Experiment No. 1

Aim: Write a program to implement the quick sort.

Problem Description

1 . Quick sort is based on an algorithmic design pattern called divide-and-conquer.


2 . To reduce the chances of the worst case we have implemented Quicksort using
randomization.
3 . Here we will be selecting the pivot randomly.
Problem Solution
1. Randomly select pivot value from the given subpart of the array.
2. Partition that subpart so that the values left of the pivot are smaller and to the right are
greater from the pivot.
3. Consider both as new sub-array and repeat step 1 until only one element left in subpart.
4 . Display the result.
5 . Exit.
Program/Source Code

C++ program to implement Quick sort using randomization.

#include<iostream>
#include<cstdlib>

// Swapping two values.


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

// Partitioning the array on the basis of values at high as pivot value.


int Partition(int a[], int low, int high)
{
int pivot, index, i;
index = low;
pivot = high;

// Getting index of pivot.


for(i=low; i < high; i++)
{
if(a[i] < a[pivot])
{
swap(&a[i], &a[index]);
index++;
}
}
// Swapping value at high and at the index obtained.
swap(&a[pivot], &a[index]);

return index;
}

// Random selection of pivot.


int RandomPivotPartition(int a[], int low, int high)
{
int pvt, n, temp;
n = rand();
// Randomizing the pivot value in the given subpart of array.
pvt = low + n%(high-low+1);

// Swapping pvt value from high, so pvt value will be taken as pivot while
partitioni
ng.
swap(&a[high], &a[pvt]);

return Partition(a, low, high);


}

// Implementing QuickSort algorithm.


int QuickSort(int a[], int low, int high)
{
int pindex;
if(low < high)
{
// Partitioning array using randomized pivot.
pindex = RandomPivotPartition(a, low, high);
// Recursively implementing QuickSort.
QuickSort(a, low, pindex-1);
QuickSort(a, pindex+1, high);
}
return 0;
}

int main()
{
int n, i;
cout<<"\nEnter the number of data element to be sorted: ";
cin>>n;

int arr[n];
for(i = 0; i < n; i++)
{
cout<<"Enter element "<<i+1<<": ";
cin>>arr[i];
}

QuickSort(arr, 0, n-1);

// Printing the sorted data.


cout<<"\nSorted Data ";
for (i = 0; i < n; i++)
cout<<"->"<<arr[i];
return 0;
}
Program Explanation
1. Take input of data.
2. Call QuickSort() function.
3. Through RandomPivotPartition(), select pivot randomly.
4. Create a partition of the array on the basis of the pivot so that the element to the left of the
pivot are smaller and to the right are greater.
5. Recursively insert the partitions into QuickSort() and repeat step 2 until low is lesser than
high.
6 . Return to main and display the result.
7 . Exit.

Output:

Enter the number of data element to be sorted: 10


Enter element 1: 23
Enter element 2: 9876
Enter element 3: 459
Enter element 4: 650
Enter element 5: 32
Enter element 6: 9
Enter element 7: 4705
Enter element 8: 1
Enter element 9: 17
Enter element 10: 3

Sorted Data ->1->3->9->17->23->32->459->650->4705->9876


Experiment No. 2

Aim: Write a program to implement the merge sort.

1. Merge-sort is based on an algorithmic design pattern called divide-and-conquer.


2. It forms tree structure.
3. The height of the tree will be log(n).
4. we merge n element at every level of the tree.

1 Problem Solution
1. Split the data into two equal half until we get at most one element in both half.
2. Merge Both into one making sure the resulting sequence is sorted.
3. Recursively split them and merge on the basis of constraint given in step 1.
4. Display the result.
5. Exit.

2 Program/Source Code
C++ program to implement Merge sort.

#include <iostream>

// A function to merge the two half into a sorted data.


void Merge(int *a, int low, int high, int mid)
{
// We have low to mid and mid+1 to high already sorted.
int i, j, k, temp[high-low+1];
i = low;
k = 0;
j = mid + 1;

// Merge the two parts into temp[].


while (i <= mid && j <= high)
{
if (a[i] < a[j])
{
}
}

}
else
{
t = a[i]; k++;
e i++;
m
p
[
k temp[k] = a[j];
] k++;
j++;

// Insert all the remaining values from i to mid into temp[].


while (i <= mid)
{
temp[k] = a[i];
k++;
i++;
}
// Insert all the remaining values from j to high into temp[].
while (j <= high)
{
temp[k] = a[j];
k++;
j++;
}

// Assign sorted data stored in temp[] to a[].


for (i = low; i <= high; i++)
{
a[i] = temp[i-low];
}
}

// A function to split array into two parts.


void MergeSort(int *a, int low, int high)
{
int mid;
if (low < high)
{
mid=(low+high)/2;
// Split the data into two half.
MergeSort(a, low, mid);
MergeSort(a, mid+1, high);

// Merge them to get sorted output.


Merge(a, low, high, mid);
}
}

int main()
{
int n, i;
cout<<"\nEnter the number of data element to be sorted: ";
cin>>n;

int arr[n];
for(i = 0; i < n; i++)
{
cout<<"Enter element "<<i+1<<": ";
cin>>arr[i];
}

MergeSort(arr, 0, n-1);
// Printing the sorted data.
cout<<"\nSorted Data ";
for (i = 0; i < n; i++)
cout<<"->"<<arr[i];
return 0;
}

3 Program Explanation:
1. Take input of data.
2. Call MergeSort() function.
3. Recursively split the array into two equal parts.
4. Split them until we get at most one element in both half.
5. Combine the result by invoking Merge().
6. It combines the individually sorted data from low to mid and mid+1 to high.
7. Return to main and display the result.
8. Exit.

4 Output:
Enter the number of data element to be sorted: 10
Enter element 1: 23
Enter element 2: 987
Enter element 3: 45
Enter element 4: 65
Enter element 5: 32
Enter element 6: 9
Enter element 7: 475
Enter element 8: 1
Enter element 9: 17
Enter element 10: 3

Sorted Data ->1->3->9->17->23->32->45->65->475->987


5 Experi
ment No. 3

Aim: Write a program to implement the fractional knapsack problem.

Description: This is a C++ Program to solve fractional knapsack. The knapsack problem
or rucksack problem is a problem in combinatorial optimization: Given a set of items,
each with a mass and a value, determine the number of each item to include in a
collection so that the total weight is less than or equal to a given limit and the total value
is as large as possible. It derives its name from the problem faced by someone who is
constrained by a fixed-size knapsack and must fill it with the most valuable items.

/* program to implement fractional knapsack problem using greedy programming */

#include<iostream
> using
namespace std; int
main()
{
int array[2][100], n, w, i, curw, used[100], maxi = -1, totalprofit = 0;

//input number of objects


cout << "Enter number of objects: ";
cin >> n;

//input max weight of knapsack


cout << "Enter the weight of the knapsack: ";
cin >> w;

/* Array's first row is to store weights


second row is to store profits */
for (i = 0; i < n; i++)
{
cin >> array[0][i] >> array[1][i];
}
for (i = 0; i < n; i++)
{
used[i] = 0;
}
curw = w;

//loop until knapsack is full


while (curw >= 0)
{
maxi = -1;

//loop to find max profit object


for (i = 0; i < n; i++)
{
if ((used[i] == 0) && ((maxi == -1) || (((float) array[1][i]
/ (float) array[0][i]) > ((float) array[1][maxi]
/ (float) array[0][maxi]))))
{
maxi = i;
}
}
used[maxi] = 1;

//decrease current wight


curw -= array[0][maxi];

//increase total profit


totalprofit += array[1][maxi];
if (curw >= 0)
{
cout << "\nAdded object " << maxi + 1 << " Weight: "
<< array[0][maxi] << " Profit: " << array[1][maxi]
<< " completely in the bag, Space left: " << curw;
}
else
{
cout << "\nAdded object " << maxi + 1 << " Weight: "
<< (array[0][maxi] + curw) << " Profit: "
<< (array[1][maxi] / array[0][maxi]) * (array[0][maxi]
+ curw) << " partially in the bag, Space left: 0"
<< " Weight added is: " << curw + array[0][maxi];
totalprofit -= array[1][maxi];
totalprofit += ((array[1][maxi] / array[0][maxi]) * (array[0][maxi]
+ curw));
}
}

//print total worth of objects filled in knapsack


cout << "\nBags filled with objects worth: " << totalprofit;
return 0;
}

Output:

Enter number of objects: 3


Enter the weight of the
knapsack: 50 10 60
20 100
30 120

Added object 1 Weight: 10 Profit: 60 completely in the bag, Space left:


40 Added object 2 Weight: 20 Profit: 100 completely in the bag, Space
left: 20
Added object 3 Weight: 20 Profit: 80 partially in the bag, Space left: 0 Weight added
is: 20 Bags filled with objects worth: 240
Experiment No. 4

Aim: Write a program to implement the heap

sort.

Problem Description
1. Heap sort is a comparison based algorithm.
2. It is improved version of selection sort.

Problem Solution
1. Build a max heap using the given data element.
2. Delete the root node repeatedly.
3. Store the node at the end of the array.
4. Display the result.
5. Exit.

Program/Source Code
C++ program to implement Heap Sort.

#include <iostream>

// A function to
heapify the array. void
MaxHeapify(int a[],
int i, int n)
{
int j,
temp;
temp =
a[i]; j =
2*i;

while (j <= n)
{
if (j < n && a[j+1] >
a[j]) j = j+1;

// Break if parent value is already greater than child


value. if (temp > a[j])
break;

// Switching value with the parent node if temp <


a[j]. else if (temp <= a[j])
{
a[j/2] =
a[j]; j =
2*j;
}
}
a[j/2] =
temp;
return;
}
void HeapSort(int a[], int n)
{
int i, temp;
for (i = n; i >= 2; i--)
{

// Storing maximum value at the end.


temp = a[i];
a[i] = a[1];
a[1] = temp;

// Building max heap of remaining element.


MaxHeapify(a, 1, i - 1);
}
}
void Build_MaxHeap(int a[], int n)
{
int i;
for(i = n/2; i >= 1; i--)
MaxHeapify(a, i, n);
}
int main()
{
int n, i;
cout<<"\nEnter the number of data element to be sorted: ";
cin>>n;
n++;
int arr[n];
for(i = 1; i < n; i++)
{
cout<<"Enter element "<<i<<": ";
cin>>arr[i];
}

// Building max heap.


Build_MaxHeap(arr, n-1);
HeapSort(arr, n-1);

// Printing the sorted data.


cout<<"\nSorted Data ";

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


cout<<"->"<<arr[i];

return 0;
}
6 Program Explanation
1. Take input of data.
2. Call Build MaxHeap() function with ‘arr’ the array of data and ‘n-1’ the number of values,
in the argument list.
3. After building the max heap call HeapSort().
4. Switch the root value of heap with the last index value of array since root value is
highest among all.
5. Decrement the last index value.
6. Repeat it for all the element.
7. Return to main and display the result.
8. Exit.

7 Output:
Enter the number of data element to be
sorted: 10 Enter element 1: 9
Enter element 2: 6
Enter element 3: 4
Enter element 4: 3
Enter element 5: 8
Enter element 6: 7
Enter element 7: 5
Enter element 8: 2
Enter element 9: 0
Enter element 10: 1

Sorted Data ->0->1->2->3->4->5->6->7->8->9

Experiment No.

5 Aim: Write program to implement the binary

Problem
search. Description
We have to write a C++ Program which either finds the position of an element in an array or detects
the presence of an element in an array using Binary Search Algorithm.

Expected Input and Output

Case 1. Average Case: When the element to be searched for is any random element from the
array. If the input array is {1, 2, 3, 4, 5, 6}
and the element to be searched for is 6,
then the output will be SEARCH SUCCESSFUL.

Case 2. Best case: When the element to be searched for is the middle element of the
array. If the input array is {-3, 31, 66}
and the element to be searched is 31,
then the output will be SEARCH SUCCESSFUL.
Case 3. Worst Case: When the element searched for is absent and it is either smaller or
greater than all the elements.
If the input array is {1, 1, 3, 6, 9}
and the element to be searched for
is 10, then the output will be
SEARCH FAILED

8 Problem Solution
We will be having an array of numbers, we just need to find out the position of an element in
the array if it is present. It can be done using Linear Search but it takes up a lot of time, so we
need a better searching algorithm that performs the same task but in less time in comparison
to Linear Search. In worst case Linear Search takes O(n) time, but Binary Search takes O(log
n) time.

9 Program/Source Code
Here is source code of the C++ Program to find the position of an element requested by the
user using Binary Search Algorithm using iteration.

/*
* C++ program to accept N numbers sorted in ascending order
* and to search for a given number using Binary Search.
* Report success or failure.
*/

#include
<iostream>
using
namespace
std; class BS
{
public:

/*
* Binary Search function
*/
void BinarySearch(int array[], int keynum, int num)
{
int low = 1;
int high = num;
int mid;
do
{
mid = (low + high) / 2;
if (keynum < array[mid])
{
high = mid - 1;
}
else if (keynum > array[mid])
{
low = mid + 1;
}
}
while (keynum != array[mid] && low <= high);
if (keynum == array[mid])
{
cout<<"SEARCH SUCCESSFUL \n";
}
else
{
cout<<"SEARCH FAILED \n";
}
}
};
int main()
{
int array[10];
int i, j, num, temp, keynum;
int low, mid, high;
cout<<"Enter the value of num \n";
cin>>num;
cout<<"Enter the elements one by one \n";
for (i = 0; i < num; i++)
{
cin>>array[i];
}

/*
* Bubble sort
*/
for (i = 0; i < num; i++)
{
for (j = 0; j < (num - i - 1); j++)
{
if (array[j] > array[j + 1])
{
temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
cout<<"Enter the element to be searched \n";
cin>>keynum;
// Binary searching begins
BS b1;
b1.BinarySearch(array, keynum, num);
return 0;
}

10 Program Explanation
1. Here in this program we have first requested the array of numbers and the value to be
searched from the user.
2. Since binary search is applied upon a sorted array we have created a separate bubble
sort function to sort the array before searching.
3. After sorting the array we have passed the array to the function called
BinarySearch(array, keynum, num) having array, key and the size of array as its
parameters.
4. In BinarySearch(array, keynum, num) we first find the middle index of the array, and
then compare the key with the middle element of array i.e. array[middle].
5. If key is less than the middle element of array we divide the array in to two halves i.e. low to
mid-1 and (mid+1) to high, where mid is the middle index, low is the starting and high is the ending
index of the array. After dividing the array we start searching in the left half of the array i.e. low to
mid-1.
6. If the key is greater than the middle element then we search in the right half of the array
i.e mid+1 to high.
7. In each iteration we divide the array until it has only 1 element left.
8. If we are able to find the element we print “SEARCH SUCCESSFUL” otherwise we print
“SEARCH FAILED”.

11 Output:
1. Enter the value of num
6
Enter the elements one by one
123456
Enter the element to be searched
6
SEARCH SUCCESSFUL

2. Enter the value of num


3
Enter the elements one by one
-3 31 66
Enter the element to be searched
31
SEARCH SUCCESSFUL

3. Enter the value of num


5
Enter the elements one by one
11369
Enter the element to be searched
10
SEARCH FAILED

You might also like