Professional Documents
Culture Documents
Time: 10 am - 1 pm & 2 pm - 5 pm
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:
Lab Tasks
Task 1:
Implement Bubble sort, Selection sort, Insertion sort algorithms in C++.
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));
return arr;
}
int main() {
const int n = 10;
//bubbleSort(arr,n);
int main() {
// bubbleSort(arr,n);
selectionSort(arr,n);
// insertionSort(arr,n);
cout << "Time taken by the selection-sort array of size " << n
<< " is " << duration_cast < milliseconds > (end-start).count() <<
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.
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:
int main() {
//selectionSort(arr,n);
insertionSort(arr,n);
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
Selection sort:
For selection sort, the time complexity is O(n^2) for both best and worst cases. Hence
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