You are on page 1of 13

Department of Computing

School of Electrical Engineering and Computer Science

CS-250: Data Structure and Algorithms


Class: BESE 10AB

Lab 8: Implementation of Sorting Algorithms and Complexity


Analysis

Date: 12th Nov 2021

Time: 10 am - 1 pm & 2 pm - 5 pm

CS250: Data Structures and Algorithms Page 1


Instructor: : Dr. Asad W. Malik (A)

Dr. Ahsan Saadat (B)

Class: BESE 11B


Name: Shehryar Saqib
CMS ID=347703

CS250: Data Structures and Algorithms Page 2


Lab 8: Implementation of Sorting Algorithms and Complexity
Analysis

Introduction

In this lab, you will implement three sorting algorithms and compare them.

Objectives
Objective of this lab is to implement insertion sort and merge sort and compare the running times
for both sorting algorithms.

Tools/Software Requirement
Visual Studio C++

Helping Material
Lecture slides, text book

Description:

Bubble Sort:
Bubble sort is a popular sorting algorithm, which is quite simple to implement. The pseudo code
is as follows:

Selection Sort:
Selection sort is a popular sorting algorithm, which is quite simple to implement. The pseudo
code is as follows:

CS250: Data Structures and Algorithms Page 3


Insertion Sort:
Insertion sort is a popular sorting algorithm, which is quite simple to implement. The pseudo
code is as follows:

Lab Tasks

Task 1:
Implement Bubble sort, Selection sort, Insertion sort algorithms in C++.

Task 2 (average case complexity):


The next step is to compare the two algorithms. Generate arrays of random numbers in the range
1 to 100 with sizes 100, 1000, 10000, 100000, and 1000000. Compare the running times of the
three algorithms on each array. How do they compare? Are the results what you expected, and
why? Answer the questions in the solution section.

Task 3 (best and worst case complexity):


Now sort the arrays using stl::sort, once in ascending order and then in descending order. Given
both sorted arrays as inputs to all three algorithms and compute their running time. The running

CS250: Data Structures and Algorithms Page 4


time of which algorithm shows most variations based on the structure of the input and why?
Answer the questions in the solution section.

Important Note: Practice your knowledge of OOP with C++ when creating a solution.
Remember to comment your code properly. Inappropriate or no comment may result in
deduction of marks.

Solution:

Solution
Task 1:

#include <iostream>
#include <ctime>
#include <chrono>
#include <bits/stdc++.h>
using namespace std::chrono;
using namespace std;

int* generatingRandomArray(int n) {
/* generates an integer array of size n containing integers between 0 and 100 */
int* arr = new int[n];
srand(time(0));

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


arr[i] = rand() % 100 + 1; // random integer between 0, 100
}

return arr;
}

void bubbleSort(int* arr,int size) {

for(int i=size-1; i>0; i--) {


for(int j=0; j<size-1; j++) {
if(arr[j] > arr[j+1]) { // if the current element is smaller than the next element,
swap
swap(arr[j], arr[j+1]);
}
}
}

CS250: Data Structures and Algorithms Page 5


}

void selectionSort(int* arr,int size) {


int indexOfmin;
// this loop decreases the size of subarray by 1 in each iteration
for(int i=0; i<size-1; i++) {
// pick the first element of the unsorted array, we will replace this with the smallest
int later
indexOfmin = i;
// loop through the unsorted array in search of smaller int
for(int j=i+1; j<size; j++) {
if(arr[j] < arr[indexOfmin]) {
indexOfmin = j;
}
}
swap(arr[i], arr[indexOfmin]);
}
}

void insertionSort(int* arr,int size) {


int hole, temp;
for(int i=1; i<=size-1; i++) {
temp = arr[i]; //storing the value and index of array in temporary variables
hole = i;
//Sorted part of array is pushed to left and unsorted part of array is towards right
while( hole>0 && arr[hole-1]>temp) { //Comparison
arr[hole] = arr[hole-1];
hole=hole-1;
}
arr[hole] = temp;
}
}

int main() {
const int n = 10;

int* arr = generatingRandomArray(n);

cout << "Before sorting: " << endl;


for(int i=0; i<n; i++) {
cout << arr[i] << " ";
}

//bubbleSort(arr,n);

CS250: Data Structures and Algorithms Page 6


selectionSort(arr,n);
//insertionSort(arr,n);

cout << "\nAfter selection-sorting: " << endl;


for(int i=0; i<n; i++) {
cout << arr[i] << " ";
}

Task 2 : (includes only the changes made for task 2.)

Note: We included chrono in task1.

int main() {

const int n = 1000;

int* arr = generatingRandomArray(n);

CS250: Data Structures and Algorithms Page 7


auto start = high_resolution_clock::now();

// bubbleSort(arr,n);

selectionSort(arr,n);

// insertionSort(arr,n);

auto end = high_resolution_clock::now();

cout << "Time taken by the selection-sort array of size " << n

<< " is " << duration_cast < milliseconds > (end-start).count() <<

"ms" << endl;

CS250: Data Structures and Algorithms Page 8


Bubble sort shows O(n^2) time complexity. . As we make the input size 10

times larger, the time taken sort the array increases around 100 times.

Selection sort scales by O(n^2). As we make the input size 10 times larger,

the time taken sort the array increases around 100 times. This is still

slightly better than bubble sort as we can see by its time taken of size

100000.

CS250: Data Structures and Algorithms Page 9


Insertion sort is the best algorithm by far we have seen in this lab. Although

average case time complexity is O(n^2), insertion sort may or may not scan

the whole array since it depends on the initial sortedness of the array due to

the while condition. Thus, insertion sort gets the job done much faster than

other two.

Task 3:

Code change in main function:

int main() {

const int n = 100000;

int* arr = generatingRandomArray(n);

//sort(arr, arr + n); // ascending order

sort(arr, arr + n, greater<int>()); // descending order

auto start = high_resolution_clock::now();

CS250: Data Structures and Algorithms Page 10


//bubbleSort(arr,n);

//selectionSort(arr,n);

insertionSort(arr,n);

auto end = high_resolution_clock::now();

cout << "Time taken insertion-sort on (descending) sorted array of size "

<< n << " is " << duration_cast < milliseconds > (end-start).count() << "ms"

<< endl;

Bubble sort:

Ascending is the best case and the time complexity is O(n), so same input size array needs

CS250: Data Structures and Algorithms Page 11


less time. Descending is the worst case and here the time complexity is O(n^2).

Selection sort:

For selection sort, the time complexity is O(n^2) for both best and worst cases. Hence

almost same time is needed for sorting both arrays.

Insertion sort:

Insertion sort doesn’t require to do anything in the array when it is already sorted

in ascending order. Because all the subarrays is already sorted and only

comparisons are done without any swapping. In worst case, the time complexity

is O(n^2) which explains the time it took for it to sort the array.

Conclusion:

Insertion sort should show most variance in time as it needs no time if array is in

ascending order but requires a lot of time in descending order.

CS250: Data Structures and Algorithms Page 12


Deliverables
Compile a single word document by filling in the solution part and submit this Word file on LMS.
This lab grading policy is as follows: The lab is graded between 0 to 10 marks. The submitted
solution can get a maximum of 5 marks. At the end of each lab or in the next lab, there will be a
viva related to the tasks. The viva has a weightage of 5 marks. Insert the solution/answer in this
document. You must show the implementation of the tasks in the designing tool, along with
your complete Word document to get your work graded. You must also submit this Word
document on the LMS. In case of any problems with submissions on LMS, submit your Lab
assignments by emailing it to Mr. Aftab Hussain: aftab.hussain1@seecs.edu.pk.

CS250: Data Structures and Algorithms Page 13

You might also like