Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Lab 1-5

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

EXPERIMENT NO- 1

DATE- 07/09/2022

Objective:
Write a program for recursive Binary and Linear search.

LINEAR SEARCH –
Algorithm:
Step.1: Start
Step.2: Display the list and input the key to search.
Step.3: If list size < 0, then return -1.
Step.4: If current last element = key, then return current size.
Else, make recursive call with size = size - 1.
Step.5: End.
Code:
#include <stdio.h>
int RecursiveLS(int arr[], int value, int index, int n)
{
int pos = 0;
if(index >= n)
{
return 0;
}
else if (arr[index] == value)
{
pos = index + 1;
return pos;
}

else
{
return RecursiveLS(arr, value, index+1, n);
}
return pos;
}
int main()
{
int n, value, pos, m = 0, arr[100],i;
printf("Enter the total elements in the array ");
scanf("%d", &n);

printf("Enter the array elements\n");


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

printf("Enter the element to search ");


scanf("%d", &value);

pos = RecursiveLS(arr, value, 0, n);


if (pos != 0)
{
printf("Element found at pos %d ", pos);
}
else

{
printf("Element not found");
}
return 0;
printf("\nCODE BY PRAKHAR KUMAR SINGH(2000970130078)");
}
Output:

BINARY SEARCH
Algorithm:
Step.1: Start
Step.2: Display sorted list and input key to search.
Step.3: Initialize pointers low = 0 and high = size – 1.
Step.4: If low <= high, repeat steps 5 to 7
Else, return -1.
Step.5: Calculate middle index, mid = low + high / 2.
Step.6: If mid element = key, return mid index.
Step.7: If mid element > key, make call with high = mid – 1
Else, make recursive call with low = mid + 1.
Step.8: End.

Code:
#include <stdio.h>
int iterativeBinarySearch(int array[], int start_index, int end_index, int
element){
while (start_index <= end_index){
int middle = start_index + (end_index- start_index )/2;
if (array[middle] == element)
return middle;
if (array[middle] < element)
start_index = middle + 1;
else
end_index = middle - 1;
}
return -1;
}
int main(voids)
{
int n, value, pos, m = 0, array[100],i,element;
printf("Enter the total elements in the array ");
scanf("%d", &n);

printf("Enter the array elements\n");


for (i = 0; i < n; i++)
{
scanf("%d", &array[i]);
}
printf("Enter the element to search "); scanf("%d",
&element);
int found_index = iterativeBinarySearch(array, 0, n-1, element);
if(found_index == -1 ) {
printf("Element not found in the array ");
}
else {
printf("Element found at index : %d",found_index);
}
return 0;
printf("\nCODE BY PRAKHAR KUMAR SINGH(2000970130078)");

}
Output:

Result:
The programs for linear search have been implemented successfully with the
time complexities as follows:
Recursive approach: O(n) – Worst and average case & O(1) – Best case.
And space complexity: O(1) – recursive and iterative approach.
The programs for binary search have been implemented successfully with time
complexities as follows:
Recursive approach: O(log n) – Worst and average case & O(1) – Best
case. And space complexity: O(log n) – recursive and O(1) – iterative approach.
EXPERIMENT NO- 2
DATE- 14/09/2022

Objective:
Write a program to implement Heap sort.
Algorithm:
Step.1: Start
Step.2: Input list (a) from user to sort.
Step.3: Build a max heap (heapify) from the given list.
Step.4: Swap the root element from the last element of the heap.
Swap(a[n],a[0]).
Step.5: Reduce the size of heap by 1 (size = size – 1).
Step.6: Heapify the remaining elements of new size by calling heapify on root
node.
Step.7: Repeat step 4, 5, and 6 if heap size > 2.
Step. 8: Display the sorted list.
Step.9: End.

Code:
#include <stdio.h>
/* function to heapify a subtree. Here 'i' is the
index of root node in array a[], and 'n' is the size of heap. */
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/
void heapSort(int a[], int n)
{
for (int i = n / 2 - 1; i >= 0; i--)
heapify(a, n, i);
// 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 */
void printArr(int arr[], int n)
{
for (int i = 0; i < n; ++i)
{
printf("%d", arr[i]);
printf(" ");
}

}
int main()
{
int a[] = {48, 10, 23, 43, 28, 26, 1};
int n = sizeof(a) / sizeof(a[0]);
printf("Before sorting array elements are - \n");
printArr(a, n);
heapSort(a, n);
printf("\nAfter sorting array elements are - \n");
printArr(a, n);
printf("\nCODE BY PRAKHAR KUMAR SINGH(2000970130078)");
return 0;
}
Output:

Result:
Thus, the above-mentioned program was implemented successfully with:
Time complexity: O(n log n) in all three cases.
Space complexity: O(1)
EXPERIMENT NO- 3
DATE- 14/09/2022

Objective:
Write a program to implement Merge sort.

Algorithm:
Step.1: Start
Step.2: Find the middle index of the list (m = l + r / 2).
Step.3: Divide the list from middle.
Step.4: Call merge sort for the first half and second half.
mergeSort(a, l, m); mergeSort(a, m +1, r);
Step.5: If l < r, then repeat steps 2 to 4.
Step.6: Merge the sorted half lists and display it.
Step.7: End.
Code:
#include <stdio.h>

/* Function to merge the subarrays of a[] */


void merge(int a[], int beg, int mid, int end)
{
int i, j, k;
int n1 = mid - beg + 1;
int n2 = end - mid;

int LeftArray[n1], RightArray[n2]; // temporary arrays

/* copy data to temp arrays */


for (int i = 0; i < n1; i++)
LeftArray[i] = a[beg + i];
for (int j = 0; j < n2; j++)
RightArray[j] = a[mid + 1 + j];

i = 0; /* initial index of first sub-array */


j = 0; /* initial index of second sub-array */
k = beg; /* initial index of merged sub-array */

while (i < n1 && j < n2)


{
if (LeftArray[i] <= RightArray[j])
{
a[k] = LeftArray[i];
i++;
}
else
{
a[k] = RightArray[j];
j++;
}
k++;
}
while (i < n1)
{
a[k] = LeftArray[i];
i++;
k++;
}
while (j < n2)
{
a[k] = RightArray[j];
j++;
k++;
}
}

void mergeSort(int a[], int beg, int end)


{
if (beg < end)
{
int mid = (beg + end) / 2;
mergeSort(a, beg, mid);
mergeSort(a, mid + 1, end);
merge(a, beg, mid, end);
}
}

/* Function to print the array */


void printArray(int a[], int n)
{
int i;
for (i = 0; i < n; i++)
printf("%d ", a[i]);
printf("\n");
}

int main()
{
int n;
printf("Enter the size: ");
scanf("%d",&n);
int arr[n];
printf("Enter the element of array: ");
for(int i=0;i<n;i++)
{
scanf("%d",&arr[i]);

}
mergeSort(arr, 0, n - 1);
printf("The Sorted Array is : ");
printArray(arr, n);
printf("\nCODE BY PRAKHAR KUMAR SINGH(2000970130078)");
return 0;
}

Output:

Result:
Thus, the above-mentioned program for merge sort implemented successfully
with:
Time complexity: O(n log n) – in all three cases.
Space complexity: O(n).
EXPERIMENT NO- 4
DATE- 21/09/2022

Objective:
Write a program to implement Selection Sort.

Algorithm:
SELECTION SORT(arr, n)
Step 1: Repeat Steps 2 and 3 for i = 0 to n-1
Step 2: CALL SMALLEST(arr, i, n, pos)
Step 3: SWAP arr[i] with arr[pos]
[END OF LOOP]
Step 4: EXIT

SMALLEST (arr, i, n, pos)


Step 1: [INITIALIZE] SET SMALL = arr[i]
Step 2: [INITIALIZE] SET pos = i
Step 3: Repeat for j = i+1 to n
if (SMALL > arr[j])
SET SMALL = arr[j]
SET pos = j
[END OF if]
[END OF LOOP]
Step 4: RETURN pos

Code:
#include <stdio.h>

void swap(int *xp, int *yp)


{
int temp = *xp;
*xp = *yp;
*yp = temp;
}

void selectionSort(int arr[], int n)


{
int i, j, min_idx;

// One by one move boundary of unsorted


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

min_idx = i;
for (j = i+1; j < n; j++)
if (arr[j] < arr[min_idx])
min_idx = j;

// Swap the found minimum element


with the first element
if(min_idx != i)
swap(&arr[min_idx],
&arr[i]);
}
}

/* Function to print an array */


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

// Driver program to test above functions


int main()
{
int arr[] = {64, 25, 12, 22, 11};
int n = sizeof(arr)/sizeof(arr[0]);
selectionSort(arr, n);
printf("Sorted array: \n");
printArray(arr, n);
printf("\nCODE BY PRAKHAR KUMAR
SINGH(2000970130078)");
return 0;
}
Output:

Result:
Thus, the above-mentioned program for merge sort implemented successfully
with:
Time complexity: O(n2) – in all three cases.
Space complexity: O(1).
EXPERIMENT NO- 5
DATE- 21/09/2022

Objective:
Write a program to implement Insertion Sort.

Algorithm:
Step 1: If it is the first element, it is already sorted. Return1;
Step 2: Pick next element
Step 3: Compare with all elements in the sorted sub-list
Step 4: Shift all the elements in the sorted sub-list that is greater than the
value to be sorted
Step 5: Insert the value
Step 6 - Repeat until list is sorted

Code:
#include <stdio.h>

// Function to print an array


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

void insertionSort(int array[], int size) {


for (int step = 1; step < size; step++) {
int key = array[step];
int j = step - 1;

// Compare key with each element on the left of it until an element smaller than
// it is found.
// For descending order, change key<array[j] to key>array[j].
while (key < array[j] && j >= 0) {
array[j + 1] = array[j];
--j;
}
array[j + 1] = key;
}
}

// Driver code
int main() {
int data[] = {9, 5, 1, 4, 3};
int size = sizeof(data) / sizeof(data[0]);
insertionSort(data, size);
printf("Sorted array in ascending order:\n");
printArray(data, size);
printf("\nCODE BY PRAKHAR KUMAR SINGH(2000970130078)");
}

Output:

Result:
Thus, the above-mentioned program for merge sort implemented successfully
with:
Time complexity:
Best Case- O(n)
Average Case- O(n2)
Worst Case- O(n2)

Space complexity: O(1).


EXPERIMENT NO- 6
DATE- 28/09/2022

Objective:
Write a program to implement Quick Sort.

Algorithm:
Step 1 - Consider the first element of the list as pivot (i.e., Element at first
position in the list).
Step 2 - Define two variables i and j. Set i and j to first and last elements of the
list respectively.
Step 3 - Increment i until list[i] > pivot then stop.
Step 4 - Decrement j until list[j] < pivot then stop.
Step 5 - If i < j then exchange list[i] and list[j].
Step 6 - Repeat steps 3,4 & 5 until i > j.
Step 7 - Exchange the pivot element with list[j] element.

Code:
#include<stdio.h>
#include<conio.h>

void quickSort(int [10],int,int);

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

printf("Enter size of the list: ");


scanf("%d",&size);

printf("Enter %d integer values: ",size);


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

quickSort(list,0,size-1);

printf("List after sorting is: ");


for(i = 0; i < size; i++)
printf(" %d",list[i]);
printf("\nCODE BY PRAKHAR KUMAR SINGH(2000970130078)");

getch();
}

void quickSort(int list[10],int first,int last){


int pivot,i,j,temp;

if(first < last){


pivot = first;
i = first;
j = last;

while(i < j){


while(list[i] <= list[pivot] && i < last)
i++;
while(list[j] > list[pivot])
j--;
if(i <j){
temp = list[i];
list[i] = list[j];
list[j] = temp;
}
}

temp = list[pivot];
list[pivot] = list[j];
list[j] = temp;
quickSort(list,first,j-1);
quickSort(list,j+1,last);
}
}

Output:

Result:
Thus, the above-mentioned program for quick sort implemented successfully
with:
Time complexity:
Best Case- O(n log n)
Average Case- O(n log n)
Worst Case- O(n2)

You might also like