You are on page 1of 32

Lab Record

of

Design And Analysis Of Algorithms


(CSF302)

Submitted to: Submitted by:


Ms.Meghavi Rana Name-Udit Dumka
Assistant Prof. Rollno-210102337
School of Computing Section- D (P2)
DIT University 3ndYr (5th Sem)

Session 2023-24
INDEX

Date of Date of
S.no. Name of the experiment Remarks
conduction submission
1 Program to implement Insertion sort 17/aug/23 24/aug/23
2 Program to implement Selection sort 17/aug/23 24/aug/23
3 Program to implement bubble sorting 18/aug/23 24/aug/23
4 Program to implement Count sort 24/aug/23 24/aug/23
5 Program to implement Quick sort 7/sep/23 24/aug/23
6 Program to implement Merge sort 14/sept/23 24/aug/23
7 Program to implement Binary search 20/sep/23 24/aug/23
8 Program to implement Heap sort 21/sep/23 24/aug/23
Write a JAVA program to implement
9 19/oct/23 24/aug/23
Dijkstra’s Algorithm.
Write a program to implement 0-1
10 26/oct 24/aug/23
Knapsack problem.

Student Name-Udit Dumka SAP ID-1000015937 D(p2)


School of Computing
Experiment-1
Aim- Program to implement Insertion sort

Algorithm:
Insertion Sort(arr, size)
consider 0th element as sorted part
for each element from i=2 to n-1
tmp = arr[i]
for j=i-1 to 0
If a[j]>tmp
Then right shift it by one position
put tmp at current j

Program:
public class InsertionSortExample {
public static void insertionSort(int array[]) {
int n = array.length;
for (int j = 1; j < n; j++) {
int key = array[j];
int i = j-1;
while ( (i > -1) && ( array [i] > key ) ) {
array [i+1] = array [i];
i--;
}
array[i+1] = key;
}
}

public static void main(String a[]){


int[] arr1 = {9,14,3,2,43,11,58,22};
System.out.println("Before Insertion Sort");
for(int i:arr1){
System.out.print(i+" ");

Student Name-Udit Dumka SAP ID-1000015937 D(p2)


School of Computing
}
System.out.println();

insertionSort(arr1);//sorting array using insertion sort

System.out.println("After Insertion Sort");


for(int i:arr1){
System.out.print(i+" ");
}
}
}

Output:

Complexity:

Complexity of insertion sort is O(n^2)

Student Name-Udit Dumka SAP ID-1000015937 D(p2)


School of Computing
Experiment-2
Aim-Program to implement Selection Sort.

Algorithm-

function selection sort

array : array of items

size : size of list

for i = 1 to size - 1

minimum = i // set current element as minimum

for j = i+1 to n // check the element to be minimum

if array[j] < array[minimum] then

minimum = j;

end if

end for

if indexofMinimum != i then //swap the minimum element with the current element

swap array[minimum] and array[i]

end if

end for

end function

Student Name-Udit Dumka SAP ID-1000015937 D(p2)


School of Computing
Program:

import java.util.Scanner;

public class SelectionSort { public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter the number of elements: ");

int n = scanner.nextInt();

int[] arr = new int[n];

System.out.println("Enter the elements:");

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

arr[i] = scanner.nextInt();

selectionSort(arr);

System.out.println("Sorted array:");

for (int num : arr) {

System.out.print(num + " ");

scanner.close();

public static void selectionSort(int[] arr) {

int n = arr.length;

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

int minIndex = i;

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

Student Name-Udit Dumka SAP ID-1000015937 D(p2)


School of Computing
{ if (arr[j] < arr[minIndex])

{ minIndex = j;

int temp = arr[i]; arr[i] = arr[minIndex];

arr[minIndex] = temp;

// Swap arr[i] and arr[minIndex]

Output:

Complexity:
The complexity of Selection sort is O(n^2)

Student Name-Udit Dumka SAP ID-1000015937 D(p2)


School of Computing
Experiment-3

Aim-Program to implement Bubble sort


Algorithm-

begin BubbleSort(arr)
for all array elements
if arr[i] > arr[i+1]
swap(arr[i], arr[i+1])
end if
end for
return arr
end BubbleSort

Program:-

import java.util.Scanner;

public class BubbleSort

{ public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter the number of elements: ");

int n = scanner.nextInt();

int[] arr = new int[n];

System.out.println("Enter the elements:");

for (int i = 0; i < n; i++) { arr[i] = scanner.nextInt();

bubbleSort(arr);

System.out.println("Sorted array:");

for (int num : arr) {

Student Name-Udit Dumka SAP ID-1000015937 D(p2)


School of Computing
System.out.print(num + " ");

scanner.close();

public static void bubbleSort(int[] arr)

{ int n = arr.length;

boolean swapped;

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

{ swapped = false;

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

{ if (arr[j] > arr[j + 1])

{ int temp = arr[j];

arr[j] = arr[j + 1];

arr[j + 1] = temp;

swapped = true;

if (!swapped)

{ break;

Student Name-Udit Dumka SAP ID-1000015937 D(p2)


School of Computing
Output:

Complexity:

algorithm has a worst-case time complexity of O(n2). The bubble sort has a space
complexity of O(1).

Student Name-Udit Dumka SAP ID-1000015937 D(p2)


School of Computing
Experiment-4

Aim-Program to implement count sort


Algorithm:

countingSort(array, n) // 'n' is the size of array


max = find maximum element in the given array
create count array with size maximum + 1
Initialize count array with all 0's

for i = 0 to n
find the count of every unique element and
store that count at ith position in the count array
for j = 1 to max
Now, find the cumulative sum and store it in count array

for i = n to 1
Restore the array elements
Decrease the count of every restored element by 1
end countingSort

Program:
class CountingSort {

int getMax(int[] a, int n) {


int max = a[0];
for(int i = 1; i<n; i++) {
if(a[i] > max)
max = a[i];
}
return max; //maximum element from the array
}

Student Name-Udit Dumka SAP ID-1000015937 D(p2)


School of Computing
void countSort(int[] a, int n) // function to perform counting sort
{
int[] output = new int [n+1];
int max = getMax(a, n);
//int max = 42;
int[] count = new int [max+1]; //create count array with size [max+1]

for (int i = 0; i <= max; ++i)


{
count[i] = 0; // Initialize count array with all zeros
}

for (int i = 0; i < n; i++) // Store the count of each element


{
count[a[i]]++;
}

for(int i = 1; i<=max; i++)


count[i] += count[i-1]; //find cumulative frequency

/* This loop will find the index of each element of the original array in

count array, and


place the elements in output array*/
for (int i = n - 1; i >= 0; i--) {
output[count[a[i]] - 1] = a[i];
count[a[i]]--; // decrease count for same numbers
}

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


a[i] = output[i]; //store the sorted elements into main array
}
}

/* Function to print the array elements */

Student Name-Udit Dumka SAP ID-1000015937 D(p2)


School of Computing
void printArray(int a[], int n)
{
int i;
for (i = 0; i < n; i++)
System.out.print(a[i] + " ");
}

public static void main(String args[]) {


int a[] = { 11, 30, 24, 7, 31, 16, 39, 41 };
int n = a.length;
CountingSort c1 = new CountingSort();
System.out.println("\nBefore sorting array elements are - ");
c1.printArray(a, n);
c1.countSort(a,n);
System.out.println("\nAfter sorting array elements are - ");
c1.printArray(a, n);
System.out.println();
}
}

Output:

Time Complexity:

Counting sort is a linear sorting algorithm with asymptotic complexity O(n+k).

Student Name-Udit Dumka SAP ID-1000015937 D(p2)


School of Computing
Experiment-5

Aim- Program to implement quick sort

Algorithm-

QUICKSORT (array A, start, end)


{
if (start < end)
{
p = partition(A, start, end)
QUICKSORT (A, start, p - 1)
QUICKSORT (A, p + 1, end)
}
}

Partition Algorithm:

PARTITION (array A, start, end)


{
pivot ? A[end]
i ? start-1
for j ? start to end -1 {
do if (A[j] < pivot) {
then i ? i + 1
swap A[i] with A[j]
}}
swap A[i+1] with A[end]
return i+1
}

Student Name-Udit Dumka SAP ID-1000015937 D(p2)


School of Computing
Program:

import java.util.*;

class QuickSort {

public static int partition(int[] arr,intstart,int end){

int pivot = end;

int i = start-1;

for(int j=start;j<=end;j++){

if(arr[j]<=arr[pivot]){

i++;

int temp = arr[i];

arr[i] = arr[j];

arr[j] = temp;

return i;

public static void quickSort(int arr[],int start,int end){

if(start<end){

int pivot = partition(arr,start,end);

quickSort(arr,start,pivot-1);

quickSort(arr,pivot+1,end);

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

Student Name-Udit Dumka SAP ID-1000015937 D(p2)


School of Computing
System.out.println("Enter size of array:");

int n=sc.nextInt();

int arr[]=new int[n];

System.out.println("Enter elements:");

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

arr[i]=sc.nextInt();

quickSort(arr,0,n-1);

System.out.println("Sorted array is:");

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

System.out.print(arr[i]+" ");

System.out.println();

Output:

Student Name-Udit Dumka SAP ID-1000015937 D(p2)


School of Computing
Complexity:
The average time complexity of quick sort is O(N log(N))

Student Name-Udit Dumka SAP ID-1000015937 D(p2)


School of Computing
Experiment-6

Aim- Program to implement merge sort

Algorithm-

MERGE_SORT(arr, beg, end)

if beg < end


set mid = (beg + end)/2
MERGE_SORT(arr, beg, mid)
MERGE_SORT(arr, mid + 1, end)
MERGE (arr, beg, mid, end)
end of if

END MERGE_SORT

Program:

import java.util.*;

class MergeSort {

public static void merge(int[] arr,intleft,intmiddle,int right){

int leftTempArray[] = new int[middle-left+2];

int rightTempArray[] = new int[right-middle+1];

for(int i=0;i<=middle-left;i++){

leftTempArray[i] = arr[left+i];

for(int i=0;i<right-middle;i++){

rightTempArray[i] = arr[middle+1+i];

Student Name-Udit Dumka SAP ID-1000015937 D(p2)


School of Computing
leftTempArray[middle-left+1] = Integer.MAX_VALUE;

rightTempArray[right-middle] = Integer.MAX_VALUE;

int i=0,j=0;

for(int k=left;k<=right;k++){

if(leftTempArray[i]<rightTempArray[j]){

arr[k] = leftTempArray[i];

i++;

}else{

arr[k] = rightTempArray[j];

j++;

public static void mergeSort(int arr[],int left,int right){

if(right>left){

int m= (left+right)/2;

mergeSort(arr,left,m);

mergeSort(arr,m+1,right);

merge(arr,left,m,right);

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.println("Enter size of array:");

int n=sc.nextInt();

Student Name-Udit Dumka SAP ID-1000015937 D(p2)


School of Computing
int arr[]=new int[n];

System.out.println("Enter elements:");

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

arr[i]=sc.nextInt();

mergeSort(arr,0,n-1);

System.out.println("Sorted array is:");

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

System.out.print(arr[i]+" ");

System.out.println();

Output:

Student Name-Udit Dumka SAP ID-1000015937 D(p2)


School of Computing
Time complexity:
Overall, the time complexity of the Sort-Merge Join algorithm in Spark is dominated by the
sorting step, making it O(N log N)

Student Name-Udit Dumka SAP ID-1000015937 D(p2)


School of Computing
Experiment-7

Aim-Program to implement Binary Search

Algorithm:

Binary_Search(a, lower_bound, upper_bound, val)


Step 1: set beg = lower_bound, end = upper_bound, pos = - 1
Step 2: repeat steps 3 and 4 while beg <=end
Step 3: set mid = (beg + end)/2
Step 4: if a[mid] = val
set pos = mid
print pos
go to step 6
else if a[mid] > val
set end = mid - 1
else
set beg = mid + 1
[end of if]
[end of loop] Step 5: if pos = -1
print "value is not present in the array"
[end of if]
Step 6: exit

Program:
class BinarySearch {
static int binarySearch(int a[], int beg, int end, int val)
{
int mid;
if(end >= beg)
{

Student Name-Udit Dumka SAP ID-1000015937 D(p2)


School of Computing
mid = (beg + end)/2;
if(a[mid] == val)
{
return mid+1; /* if the item to be searched is present at middle

else if(a[mid] < val)


{
return binarySearch(a, mid+1, end, val);
}
else
{
return binarySearch(a, beg, mid-1, val);
}
}
return -1;
}
public static void main(String args[]) {
int a[] = {8, 10, 22, 27, 37, 44, 49, 55, 69}; // given array
int val = 37; // value to be searched
int n = a.length; // size of array
int res = binarySearch(a, 0, n-1, val); // Store result
System.out.print("The elements of the array are: ");
for (int i = 0; i < n; i++)
{
System.out.print(a[i] + " ");
}
System.out.println();
System.out.println("Element to be searched is: " + val); if (res == -1)
System.out.println("Element is not present in the array");
else
System.out.println("Element is present at " + res + " position of array");
}
}

Student Name-Udit Dumka SAP ID-1000015937 D(p2)


School of Computing
Output:

Time Complexity:
The time complexity of binary search is O(logn)

Student Name-Udit Dumka SAP ID-1000015937 D(p2)


School of Computing
Experiment-8

Aim- Program to implement heap sort.

Algorithm-

HeapSort(arr)
BuildMaxHeap(arr)
for i = length(arr) to 2
swap arr[1] with arr[i]
heap_size[arr] = heap_size[arr] ? 1
MaxHeapify(arr,1)
End

BuildMaxHeap(arr)

BuildMaxHeap(arr)
heap_size(arr) = length(arr)
for i = length(arr)/2 to 1
MaxHeapify(arr,i)
End

L = left(i)
R = right(i)
if L ? heap_size[arr] and arr[L] > arr[i]
largest = L
else
largest = i
if R ? heap_size[arr] and arr[R] > arr[largest]
largest = R
if largest != i

Student Name-Udit Dumka SAP ID-1000015937 D(p2)


School of Computing
swap arr[i] with arr[largest]
MaxHeapify(arr,largest)

End

Program-

class HeapSort
{
static void heapify(int a[], int n, int i)
{
int largest = i; // Initialize largest as root
int left = 2 * i + 1; // left child
int right = 2 * i + 2; // right child
// If left child is larger than root
if (left < n && a[left] > a[largest])
largest = left;
// If right child is larger than root
if (right < n && a[right] > a[largest])
largest = right;
// If root is not largest
if (largest != i) {
// swap a[i] with a[largest]
int temp = a[i];
a[i] = a[largest];
a[largest] = temp;

heapify(a, n, largest);
}
}
/*Function to implement the heap sort*/
static void heapSort(int a[], int n)
{
for (int i = n / 2 - 1; i >= 0; i--)
heapify(a, n, i);

Student Name-Udit Dumka SAP ID-1000015937 D(p2)


School of Computing
// One by one extract an element from heap
for (int i = n - 1; i >= 0; i--) {
/* Move current root element to end*/
// swap a[0] with a[i]
int temp = a[0];
a[0] = a[i];
a[i] = temp;

heapify(a, i, 0);
}
}
/* function to print the array elements */
static void printArr(int a[], int n)
{
for (int i = 0; i < n; ++i)
System.out.print(a[i] + " ");
}
public static void main(String args[])
{
int a[] = {45, 7, 20, 40, 25, 23, -2};
int n = a.length; System.out.print("Before sorting array elements are - \n");
printArr(a, n);
heapSort(a, n);
System.out.print("\nAfter sorting array elements are - \n");
printArr(a, n);
}
}

Output:

Time complexity: The best-case time complexity of heap sort is O(n logn).

Student Name-Udit Dumka SAP ID-1000015937 D(p2)


School of Computing
Experiment-9

Aim- Write a JAVA program to implement Dijkstra’s Algorithm.

Algorithm-
STEP: Create a visited boolean array of size = vertices, that initially contain false at each index
describing that no vertex has been visited yet.

STEP: Create an integer array called distance that contains the distance of that node from the
source node.

STEP: Mark distance[source] = 0 and the distance of other vertices to be infinity. Also, mark
visited [source] = true.

STEP: Start from the source node and explore all the neighbors of the source node that have
been marked as non-visited.

STEP: If the weight of edge + distance [currentVertex] is less than distance[vertex], then update
the distance[vertex] = weight of Egde + distance[currentVertex].

STEP: Repeat step 5 for all the unvisited neighbors of the current vertex.

STEP: Now we take the index having a minimum value from the distance array whose visited is
marked as false as the next current vertex.

STEP: Repeat until all vertices have been marked visited.

Program:

public class Dijkstra {

public static void dijkstra(int[][] graph, int source) {

int count = graph.length;

boolean[] visitedVertex = new boolean[count];

int[] distance = new int[count];


for (int i = 0; i < count; i++) {
visitedVertex[i] = false;

distance[i] = Integer.MAX_VALUE; }
distance[source] = 0;

Student Name-Udit Dumka SAP ID-1000015937 D(p2)


School of Computing
for (int i = 0; i < count; i++) {

int u = findMinDistance(distance, visitedVertex);

visitedVertex[u] = true;

for (int v = 0; v < count; v++) {

if (!visitedVertex[v] && graph[u][v] != 0 && (distance[u] + graph[u][v] <


distance[v])) {

distance[v] = distance[u] + graph[u][v]; } } }

for (int i = 0; i < distance.length; i++) {


System.out.println(String.format("Distance from %s to %s is %s", source, i,
distance[i])); } }

private static int findMinDistance(int[] distance, boolean[] visitedVertex){


int minDistance = Integer.MAX_VALUE;

int minDistanceVertex = -1;

for (int i = 0; i < distance.length; i++) {

if (!visitedVertex[i] && distance[i] < minDistance) {

minDistance = distance[i];
minDistanceVertex = i; } }

return minDistanceVertex; }
public static void main(String[] args) {
int graph[][] = new int[][] {
{ 0, 0, 1, 2, 0, 0, 0 }, { 0, 0, 2, 0, 0, 3, 0 },
{ 1, 2, 0, 1, 3, 0, 0 }, { 2, 0, 1, 0, 0, 0, 1 },
{ 0, 0, 3, 0, 0, 2, 0 }, { 0, 3, 0, 0, 2, 0, 1 },
{ 0, 0, 0, 1, 0, 1, 0 } };
Dijkstra T = new Dijkstra();
T.dijkstra(graph, 0); } }

Output:

Student Name-Udit Dumka SAP ID-1000015937 D(p2)


School of Computing
Time complexity: Time Complexity of Dijkstra's Algorithm is O ( V 2 ) but with min-
priority queue it drops down to O ( V + E l o g V ) .

Student Name-Udit Dumka SAP ID-1000015937 D(p2)


School of Computing
Experiment-10

Aim-Program to implement 0-1 Knapsack problem

Algorithm-

Dynamic-0-1-knapsack (v, w, n, W)
for w = 0 to W do
c[0, w] = 0
for i = 1 to n do
c[i, 0] = 0
for w = 1 to W do
if wi ≤ w then
if vi + c[i-1, w-wi] then
c[i, w] = vi + c[i-1, w-wi]
else c[i, w] = c[i-1, w]
else
c[i, w] = c[i-1, w]

The maximum weight W


The number of items n
The two sequences v = <v1, v2, …, vn> and w = <w1, w2, …, wn>

Program:

class Knapsack {

static int max(int a, int b) { return (a > b) ? a : b;

static int knapSack(int W, int wt[], int val[], int n)

if (n == 0 || W == 0) return 0;

if (wt[n - 1] > W)

return knapSack(W, wt, val, n - 1);

Student Name-Udit Dumka SAP ID-1000015937 D(p2)


School of Computing
else

return max(val[n - 1] + knapSack(W - wt[n - 1], wt, val, n - 1),

knapSack(W, wt, val, n - 1));

public static void main(String args[]) {

int profit[] = new int[] { 60, 100, 120 };

int weight[] = new int[] { 10, 20, 30 };

int W = 50;

int n = profit.length;

System.out.println("The maximum profit that can be obtained is: "+knapSack(W,


weight, profit, n));

} }

Output:

Time complexity:

The time complexity for the 0/1 Knapsack problem solved using DP is O(N*W) where N
denotes the number of items available and W denotes the capacity of the knapsack.

Student Name-Udit Dumka SAP ID-1000015937 D(p2)


School of Computing

You might also like