Lesson 8 Lab
Lesson 8 Lab
Lab 1: Sorting
Overview:
This lab enables you to explore different sorting methods.
After performing the lab you will be able to:
1. Demonstrate Selection sort, Quick sort, Merge sort, and Insertion sort
2. Implement a binary search algorithm
Business Scenario:
The user requires an understanding of the various sorting methods to implement sorting
programs. They will understand and implement all these methods with the help of the
detailed instructions provided below.
Detailed Instructions:
Selection Sort
1. In this program, we will implement the selection sort algorithm.
#include <stdio.h>
2. To compile and run the program, copy the source code into a .c file and compile it.
3. Once the program is compiled successfully, execute the program.
Module 8: Algorithms and Error Handling
Quick Sort
1. In this program, you will implement the quick sort algorithm.
#include <stdio.h>
#include <stdlib.h>
void display(int*,int);
int partition(int *arr, int start, int end) //Partition the array
{
int pivot = start;
int left = start , right = end;
int i , pivotVal = arr[pivot];
arr[start] = arr[right];
arr[right] = pivotVal;
return right;
}
int main()
{
int arr[]={12,32,2,56,34,23,67,122};
int nmem = sizeof(arr)/sizeof(int);
2. To compile and run the program, copy the source code into a .c file and compile it.
3. Once the program is compiled successfully, execute the program.
Module 8: Algorithms and Error Handling
Merge Sort
1. This lab will show you how to implement merge sort algorithm.
#include<stdlib.h>
#include<stdio.h>
merge(arr, l, m, r);
}
}
2. To compile and run the program, copy the source code into a .c file and compile it.
3. Once the program is compiled successfully, execute the program.
Module 8: Algorithms and Error Handling
Insertion Sort
1. Here, we will implement the insertion sort algorithm.
#include <stdio.h>
#include <math.h>
insertionSort(arr, n);
printArray(arr, n);
return 0;
Module 8: Algorithms and Error Handling
}
2. To compile and run the program, copy the source code into a .c file and compile it.
3. Once the program is compiled successfully, execute the program.
Module 8: Algorithms and Error Handling
Binary Search Algorithm
1. The lab shows how to implement binary search algorithm.
#include <stdio.h>
int main(void)
{
int arr[] = {2, 3, 4, 10, 40};
int n = sizeof(arr) / sizeof(arr[0]);
int query = 10;
int result = binarySearch(arr, 0, n - 1, query);
if (result == -1)
printf("Element is not present in array\n");
else
printf("Element is present at index %d\n", result);
return 0;
}
Module 8: Algorithms and Error Handling
2. To compile and run the program, copy the source code into a .c file and compile it.
3. Once the program is compiled successfully, execute the program.