Download as pdf or txt
Download as pdf or txt
You are on page 1of 18

Data Structures and Algorithims

CIS-318
Assignment 2

Student Name
1. Anas Zohrab

Section: A (Electronics)
Assignment No: 02 Date of Submission:
March-20-2023
Assignment Title:
Quick sort, Merge sort, Bubble Sort, Selection Sort and
Insertion sort Comparison.
Batch: Teacher:
BSEE 2019-23 Dr. Kamran Safdar
Semester Lab Engineer:
8th Mr. Ghaznooq Ahmad

Department of Electrical Engineering


2 Assignment 2 : Quick sort, Merge sort, Bubble Sort, Selection Sort and Insertion sort Comparison.

2.1 Title: Quick sort, Merge sort, Bubble Sort, Selection Sort and
Insertion sort Comparison.

2.2 Tasks:
•Generate an array of random integers.
• Run following sorting algorithms: Quick sort, Merge sort, Bubble Sort, Selection Sort
and Insertion sort.
• Store time taken by the algorithm in a separate log file.
• Vary array size from 10 to 100000.
• Use this data to benchmark given sorting algorithms
• Plot run time against data points and discuss the results in detail.

2.3 Introduction.
Quick Sort:
Quicksort works by dividing the array into smaller and smaller subarrays until each subarray has only one
element (which is already sorted). This is done by choosing a pivot element and partitioning the array
around it. All elements less than the pivot are moved to its left and all elements greater than or equal to the
pivot are moved to its right. The pivot is then in its final position in the sorted array.
Here’s an example:
Suppose we have an array of integers: [8, 5, 2, 9, 7, 6, 3]

I. We choose the last element (3) as the pivot.


II. We partition the array around the pivot. All elements less than 3 are moved to its left and all
elements greater than or equal to 3 are moved to its right: [2] + [3] + [8, 5, 9, 7, 6]
III. The pivot (3) is now in its final position in the sorted array.
IV. We recursively apply quicksort on the two subarrays on either side of the pivot: [2] and [8, 5, 9,
7, 6].
V. The first subarray ([2]) has only one element so it is already sorted.
VI. We choose a new pivot for the second subarray ([8]). Let’s say we choose the last element (6) as
our new pivot.
VII. We partition this subarray around our new pivot: [5] + [6] + [8 ,9 ,7]
VIII. Our new pivot (6) is now in its final position in this subarray.
IX. We recursively apply quicksort on these two new subarrays: [5] and [8 ,9 ,7].
X. The first subarray ([5]) has only one element so it is already sorted.
XI. We choose a new pivot for our last remaining unsorted subarray ([8]). Let’s say we choose our
last element again (7).
XII. We partition this last remaining unsorted subarray around our new pivot: [] + [7] + [8 ,9]
XIII. 13.Our new pivot (7) is now in its final position in this last remaining unsorted subarray.
XIV. 14.We recursively apply quicksort on these two new empty arrays [] and [8 ,9].
XV. 15. The first empty array [] has no elements so it doesn’t need sorting
XVI. 16.We choose a new pivot for our last remaining unsorted array ([8]). Let’s say we choose our
last element again (9).
XVII. 17.We partition this last remaining unsorted array around our new pivot: [] +[9]+[8]
XVIII. 18.Our new Pivot(9)is now in its final position
3 Assignment 2 : Quick sort, Merge sort, Bubble Sort, Selection Sort and Insertion sort Comparison.

Figure 1 Diagram shows steps taken for Quick Sort Algoritihim

Merge Sort:

Merge sort is a sorting algorithm that uses a divide-and-conquer strategy. It works by dividing an unsorted
list into n sub-lists, each containing one element, and then repeatedly merging sub-lists to produce new
sorted sub-lists until there is only one sub-list remaining 1. Here’s an example:
Suppose we have an array [38, 27, 43, 3]. The first step is to divide it into two sub-arrays: [38, 27] and [43,
3]. Then we sort each of these sub-arrays individually: [27, 38] and [3, 43]. Finally we merge these two
sorted arrays into one sorted array: [3, 27, 38, 43].

Figure 2 Diagram shows steps taken for Merge Sort Algoritihim

Insertion Sort: This algorithm works by iterating through the input array and inserting each element into its
correct position in the sorted output array. It does this by comparing each element with the elements before
4 Assignment 2 : Quick sort, Merge sort, Bubble Sort, Selection Sort and Insertion sort Comparison.

it and shifting them to make room for the current element if they are larger. This process continues until the
entire input array has been sorted.

Figure 3 Example for Insertion Sort from web.

Selection Sort: This algorithm works by iterating through the input array and selecting the smallest element
from the unsorted portion of the array and swapping it with the first element in the unsorted portion. This
process continues until all elements have been sorted. During each iteration, the algorithm divides the input
into two parts: a sorted sublist of items which is built up from left to right at the front of the list and a sublist
of the remaining unsorted items that occupy the rest of the list. The algorithm proceeds by finding the
smallest element in the unsorted sublist and exchanging it with the leftmost unsorted element, moving the
sublist boundaries one element to the right.

Figure 4 Example for Selection sort from web

Bubble Sort: This algorithm works by repeatedly iterating through the input array and comparing adjacent
elements. If two adjacent elements are out of order, they are swapped. This process continues until no more
swaps are needed, indicating that the input array has been sorted.

Figure 5 Example for Bubble Sort from web


5 Assignment 2 : Quick sort, Merge sort, Bubble Sort, Selection Sort and Insertion sort Comparison.

2.4 Results and Code


Task 1 : Generating Random Array of inetegers as employee data

1. Code:
void generateEmployees(Employee* employees, int n) {
string firstNames[] = { "Mubashir", "Huzaifah", "Ibrahim", "Anas ",
"Fahad", "Raja", "Uzair", "Hasnain", "Ammar", "Raheem" };
string lastNames[] = { "Sajid", "Ibrahim", "Shahid", "Zohrab",
"Saghir", "Khan", "Arshad", "Khan", "Sadiq", "Shamim" };

srand(time(NULL));

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


employees[i].name = firstNames[rand() % 10] + " " +
lastNames[rand() % 10];
employees[i].salary = rand() % 100000 + 50000;
}
}
2. Result:

Figure 6 Output for Random Employee names and salaries

Task 2: Run following sorting algorithms: Quick sort, Merge sort, Bubble Sort, Selection Sort and
Insertion sort.

3. Code:
6 Assignment 2 : Quick sort, Merge sort, Bubble Sort, Selection Sort and Insertion sort Comparison.

Figure 7 code for different algorithims from previous labs

Task 3: Store time taken by the algorithm in a separate log file.


4. Code:

int main() {
//vary array size from 1000 to 10000
for (int nfor = 1000; nfor < 100000; nfor = nfor + 10000)
{
const int NUM_EMPLOYEES = nfor;
Employee employees[NUM_EMPLOYEES];
generateEmployees(employees, NUM_EMPLOYEES);

// Start timer for insertion sort


high_resolution_clock::time_point t1 =
high_resolution_clock::now();
insertionSort(employees, NUM_EMPLOYEES);
high_resolution_clock::time_point t2 =
high_resolution_clock::now();
auto durationInsertion = duration_cast<microseconds>(t2 -
t1).count();

// Start timer for selection sort


t1 = high_resolution_clock::now();
selectionSort(employees, NUM_EMPLOYEES);
t2 = high_resolution_clock::now();
auto durationSelection = duration_cast<microseconds>(t2 -
t1).count();

string namesBubbleSort[NUM_EMPLOYEES];
int salariesBubbleSort[NUM_EMPLOYEES];
for (int i = 0; i < NUM_EMPLOYEES; i++) {
namesBubbleSort[i] = employees[i].name;
salariesBubbleSort[i] = employees[i].salary;
}
7 Assignment 2 : Quick sort, Merge sort, Bubble Sort, Selection Sort and Insertion sort Comparison.

// Start timer for bubble sort


t1 = high_resolution_clock::now();
bubbleSort(namesBubbleSort, salariesBubbleSort, NUM_EMPLOYEES);
t2 = high_resolution_clock::now();
auto durationBubble = duration_cast<microseconds>(t2 -
t1).count();

double salariesMergeSort[NUM_EMPLOYEES];
string namesMergeSort[NUM_EMPLOYEES];
for (int i = 0; i < NUM_EMPLOYEES; i++) {
namesMergeSort[i] = employees[i].name;
salariesMergeSort[i] = employees[i].salary;
}

// Start timer for merge sort


high_resolution_clock::time_point s1 =
high_resolution_clock::now();
mergesort(salariesMergeSort, namesMergeSort, 0, NUM_EMPLOYEES -
1);
high_resolution_clock::time_point s2 =
high_resolution_clock::now();
auto durationMerge = duration_cast<microseconds>(s2 -
s1).count();

// Copy salaries and names arrays for quicksort


double salariesQuickSort[NUM_EMPLOYEES];
string namesQuickSort[NUM_EMPLOYEES];
for (int i = 0; i < NUM_EMPLOYEES; i++) {
salariesQuickSort[i] = employees[i].salary;
namesQuickSort[i] = employees[i].name;
}

// Start timer for quicksort


t1 = high_resolution_clock::now();
quicksort(salariesQuickSort, namesQuickSort, 0, NUM_EMPLOYEES -
1);
t2 = high_resolution_clock::now();
auto durationQuickSort = duration_cast<microseconds>(t2 -
t1).count();

// Log time taken to file


ofstream logFile("sortLog.txt", ios::app);
logFile << "Time taken to sort " << NUM_EMPLOYEES << " employees
using insertion sort: " << durationInsertion << " microseconds" << endl;
logFile << "Time taken to sort " << NUM_EMPLOYEES << " employees
using selection sort: " << durationSelection << " microseconds" << endl;
logFile << "Time taken to sort " << NUM_EMPLOYEES << " employees
using Bubble sort: " << durationBubble << " microseconds" << endl;
8 Assignment 2 : Quick sort, Merge sort, Bubble Sort, Selection Sort and Insertion sort Comparison.

logFile << "Time taken to sort " << NUM_EMPLOYEES << " employees
using Merge sort: " << durationMerge << " microseconds" << endl;
logFile << "Time taken to sort " << NUM_EMPLOYEES << " employees
using Quick sort: " << durationQuickSort << " microseconds" << endl;
}
return 0;
}
5. Result:

Figure 8 Storing time taken for each algorithm in log File

2.5 Comparing using Maltab.


Code for Matlab
x = [100, 1100, 2100, 3100, 4100, 5100, 6100, 7100, 8100, 9100, 1000, 11000, 21000, 31000];
y_insertion = [144, 15854, 67187, 103604, 178501, 294192, 399235, 537842, 696521, 899022,
13776, 1469915, 4760819, 10995338];
y_selection = [27, 1798, 10661, 13562, 23372, 36117, 52204, 69840, 90797, 114982, 1383, 171608,
612857, 1368076];
y_bubble = [19, 2064, 6873, 13430, 23446, 36035, 51588, 69798, 90836, 116163, 1404, 171324,
613825, 1331341];
y_merge1 = [77, 918, 1029, 1592, 2165, 2781, 3508, 3964, 4541, 5400, 515, 6763, 13117, 19446];
y_merge2 = [136, 12006, 54309, 91288, 157109, 240597, 343186, 464375, 599179, 756718, NaN,
NaN, NaN, NaN];

plot(x, y_insertion, 'r-', x, y_selection, 'g-', x, y_bubble, 'b-', x, y_merge1, 'y-', x, y_merge2, 'm-');
legend('Insertion Sort', 'Selection Sort', 'Bubble Sort', 'Merge Sort ', 'Quick Sort');
xlabel('Number of Employees');
ylabel('Time Taken (microseconds)');
title('Sorting Algorithms Performance');

Output from MATALB

Figure 9 Linear vs Binary


9 Assignment 2 : Quick sort, Merge sort, Bubble Sort, Selection Sort and Insertion sort Comparison.

Figure 10 Matlab Graph showing difference in time complexity for all algorithims.

2.6 Questions
Q: What is meant by “N0” ?
In algorithms, N0 usually refers to the input size beyond which the algorithm's
performance starts to degrade. In other words, N0 is the threshold value for the input size
where the algorithm's time or space complexity begins to increase rapidly. The precise value
of N0 varies depending on the specific algorithm and its implementation. N0 is often used to
analyze the efficiency of an algorithm and to determine the size of the input that the
algorithm can handle within reasonable time and space constraints.

Figure 11 No for 2 different algorithims.

Q: What is “N0” in your case?


As can be seen from figure 10, Algorithms beyond value of 1000 begin to
perform completely different from each other thus in our case 1000 is value of No.
10 Assignment 2 : Quick sort, Merge sort, Bubble Sort, Selection Sort and Insertion sort Comparison.

2.7 Discussion:
The given assignment code contains five sorting algorithms to sort an array of Employee
structures based on their salaries: insertion sort, selection sort, bubble sort, merge sort, and
quicksort. The time complexity of each algorithm varies, with insertion sort, selection sort, and
bubble sort having a time complexity of O(n^2) in the worst case, while merge sort and
quicksort have a time complexity of O(n log n) in the worst case. The performance of each
algorithm is tested on an array of 100,000 employees, and the results show that the mergesort
and quicksort algorithms are significantly faster than the other three algorithms, with quicksort
being slightly faster than mergesort in this case. The results illustrate how the time complexity
of an algorithm can significantly impact its performance on large datasets.

The first function, generateEmployees, is used to create a list of employees, where each
employee has a random name and salary. The name and salary are generated using two arrays
of first and last names and the rand() function. The srand() function is called to seed the random
number generator using the current time. The second function, insertionSort, sorts the
employees based on their salaries using the insertion sort algorithm. It has a time complexity
of O(n^2) in the worst case. It iterates through the array, comparing each element with the
elements before it, and swapping them if they are not in the correct order.

The third function, selectionSort, sorts the employees based on their salaries using the selection
sort algorithm. It has a time complexity of O(n^2) in the worst case. It iterates through the
array, finding the smallest element and swapping it with the first element. It then repeats this
process for the rest of the array. The fourth function, bubbleSort, sorts the employees based on
their salaries using the bubble sort algorithm. It has a time complexity of O(n^2) in the worst
case. It iterates through the array, comparing each element with the elements after it, and
swapping them if they are not in the correct order. It repeats this process until the array is
sorted.

In addition to measuring the execution time of each sorting algorithm using the
high_resolution_clock from the chrono library, the code also saves the time taken for each
algorithm to sort the array in a separate log file. This log file contains the name of the sorting
algorithm, the size of the array, and the time taken to sort the array. This allows for further
analysis of the performance of each algorithm and enables the comparison of different datasets
and algorithm configurations. The data from the log file is imported into matlab for
visualization as shown in figure 10.

2.8 Appendix
Log File Output.

Time taken to sort 100 employees using insertion sort: 144 microseconds
Time taken to sort 100 employees using selection sort: 27 microseconds
Time taken to sort 100 employees using Bubble sort: 19 microseconds
Time taken to sort 100 employees using Merge sort: 77 microseconds
Time taken to sort 100 employees using Merge sort: 136 microseconds
Time taken to sort 1100 employees using insertion sort: 15854
microseconds
Time taken to sort 1100 employees using selection sort: 1798 microseconds
Time taken to sort 1100 employees using Bubble sort: 2064 microseconds
Time taken to sort 1100 employees using Merge sort: 918 microseconds
11 Assignment 2 : Quick sort, Merge sort, Bubble Sort, Selection Sort and Insertion sort Comparison.

Time taken to sort 1100 employees using Merge sort: 12006 microseconds
Time taken to sort 2100 employees using insertion sort: 67187
microseconds
Time taken to sort 2100 employees using selection sort: 10661
microseconds
Time taken to sort 2100 employees using Bubble sort: 6873 microseconds
Time taken to sort 2100 employees using Merge sort: 1029 microseconds
Time taken to sort 2100 employees using Merge sort: 54309 microseconds
Time taken to sort 3100 employees using insertion sort: 103604
microseconds
Time taken to sort 3100 employees using selection sort: 13562
microseconds
Time taken to sort 3100 employees using Bubble sort: 13430 microseconds
Time taken to sort 3100 employees using Merge sort: 1592 microseconds
Time taken to sort 3100 employees using Merge sort: 91288 microseconds
Time taken to sort 4100 employees using insertion sort: 178501
microseconds
Time taken to sort 4100 employees using selection sort: 23372
microseconds
Time taken to sort 4100 employees using Bubble sort: 23446 microseconds
Time taken to sort 4100 employees using Merge sort: 2165 microseconds
Time taken to sort 4100 employees using Merge sort: 157109 microseconds
Time taken to sort 5100 employees using insertion sort: 294192
microseconds
Time taken to sort 5100 employees using selection sort: 36117
microseconds
Time taken to sort 5100 employees using Bubble sort: 36035 microseconds
Time taken to sort 5100 employees using Merge sort: 2781 microseconds
Time taken to sort 5100 employees using Merge sort: 240597 microseconds
Time taken to sort 6100 employees using insertion sort: 399235
microseconds
Time taken to sort 6100 employees using selection sort: 52204
microseconds
Time taken to sort 6100 employees using Bubble sort: 51588 microseconds
Time taken to sort 6100 employees using Merge sort: 3508 microseconds
Time taken to sort 6100 employees using Merge sort: 343186 microseconds
Time taken to sort 7100 employees using insertion sort: 537842
microseconds
Time taken to sort 7100 employees using selection sort: 69840
microseconds
Time taken to sort 7100 employees using Bubble sort: 69798 microseconds
Time taken to sort 7100 employees using Merge sort: 3964 microseconds
Time taken to sort 7100 employees using Merge sort: 464375 microseconds
Time taken to sort 8100 employees using insertion sort: 696521
microseconds
Time taken to sort 8100 employees using selection sort: 90797
microseconds
Time taken to sort 8100 employees using Bubble sort: 90836 microseconds
Time taken to sort 8100 employees using Merge sort: 4541 microseconds
Time taken to sort 8100 employees using Merge sort: 599179 microseconds
Time taken to sort 9100 employees using insertion sort: 899022
microseconds
12 Assignment 2 : Quick sort, Merge sort, Bubble Sort, Selection Sort and Insertion sort Comparison.

Time taken to sort 9100 employees using selection sort: 114982


microseconds
Time taken to sort 9100 employees using Bubble sort: 116163 microseconds
Time taken to sort 9100 employees using Merge sort: 5400 microseconds
Time taken to sort 9100 employees using Merge sort: 756718 microseconds

Time taken to sort 100 employees using insertion sort: 144 microseconds
Time taken to sort 100 employees using selection sort: 27 microseconds
Time taken to sort 100 employees using Bubble sort: 19 microseconds
Time taken to sort 100 employees using Merge sort: 77 microseconds
Time taken to sort 100 employees using Merge sort: 136 microseconds
Time taken to sort 1100 employees using insertion sort: 15854
microseconds
Time taken to sort 1100 employees using selection sort: 1798 microseconds
Time taken to sort 1100 employees using Bubble sort: 2064 microseconds
Time taken to sort 1100 employees using Merge sort: 918 microseconds
Time taken to sort 1100 employees using Merge sort: 12006 microseconds
Time taken to sort 2100 employees using insertion sort: 67187
microseconds
Time taken to sort 2100 employees using selection sort: 10661
microseconds
Time taken to sort 2100 employees using Bubble sort: 6873 microseconds
Time taken to sort 2100 employees using Merge sort: 1029 microseconds
Time taken to sort 2100 employees using Merge sort: 54309 microseconds
Time taken to sort 3100 employees using insertion sort: 103604
microseconds
Time taken to sort 3100 employees using selection sort: 13562
microseconds
Time taken to sort 3100 employees using Bubble sort: 13430 microseconds
Time taken to sort 3100 employees using Merge sort: 1592 microseconds
Time taken to sort 3100 employees using Merge sort: 91288 microseconds
Time taken to sort 4100 employees using insertion sort: 178501
microseconds
Time taken to sort 4100 employees using selection sort: 23372
microseconds
Time taken to sort 4100 employees using Bubble sort: 23446 microseconds
Time taken to sort 4100 employees using Merge sort: 2165 microseconds
Time taken to sort 4100 employees using Merge sort: 157109 microseconds
Time taken to sort 5100 employees using insertion sort: 294192
microseconds
Time taken to sort 5100 employees using selection sort: 36117
microseconds
Time taken to sort 5100 employees using Bubble sort: 36035 microseconds
Time taken to sort 5100 employees using Merge sort: 2781 microseconds
Time taken to sort 5100 employees using Merge sort: 240597 microseconds
Time taken to sort 6100 employees using insertion sort: 399235
microseconds
Time taken to sort 6100 employees using selection sort: 52204
microseconds
Time taken to sort 6100 employees using Bubble sort: 51588 microseconds
13 Assignment 2 : Quick sort, Merge sort, Bubble Sort, Selection Sort and Insertion sort Comparison.

Time taken to sort 6100 employees using Merge sort: 3508 microseconds
Time taken to sort 6100 employees using Merge sort: 343186 microseconds
Time taken to sort 7100 employees using insertion sort: 537842
microseconds
Time taken to sort 7100 employees using selection sort: 69840
microseconds
Time taken to sort 7100 employees using Bubble sort: 69798 microseconds
Time taken to sort 7100 employees using Merge sort: 3964 microseconds
Time taken to sort 7100 employees using Merge sort: 464375 microseconds
Time taken to sort 8100 employees using insertion sort: 696521
microseconds
Time taken to sort 8100 employees using selection sort: 90797
microseconds
Time taken to sort 8100 employees using Bubble sort: 90836 microseconds
Time taken to sort 8100 employees using Merge sort: 4541 microseconds
Time taken to sort 8100 employees using Merge sort: 599179 microseconds
Time taken to sort 9100 employees using insertion sort: 899022
microseconds
Time taken to sort 9100 employees using selection sort: 114982
microseconds
Time taken to sort 9100 employees using Bubble sort: 116163 microseconds
Time taken to sort 9100 employees using Merge sort: 5400 microseconds
Time taken to sort 9100 employees using Merge sort: 756718 microseconds
Time taken to sort 1000 employees using insertion sort: 13776
microseconds
Time taken to sort 1000 employees using selection sort: 1383 microseconds
Time taken to sort 1000 employees using Bubble sort: 1404 microseconds
Time taken to sort 1000 employees using Merge sort: 515 microseconds
Time taken to sort 1000 employees using Quick sort: 12485 microseconds
Time taken to sort 11000 employees using insertion sort: 1469915
microseconds
Time taken to sort 11000 employees using selection sort: 171608
microseconds
Time taken to sort 11000 employees using Bubble sort: 171324 microseconds
Time taken to sort 11000 employees using Merge sort: 6763 microseconds
Time taken to sort 11000 employees using Quick sort: 1093138 microseconds
Time taken to sort 21000 employees using insertion sort: 4760819
microseconds
Time taken to sort 21000 employees using selection sort: 612857
microseconds
Time taken to sort 21000 employees using Bubble sort: 613825 microseconds
Time taken to sort 21000 employees using Merge sort: 13117 microseconds
Time taken to sort 21000 employees using Quick sort: 3813225 microseconds
Time taken to sort 31000 employees using insertion sort: 10995338
microseconds
Time taken to sort 31000 employees using selection sort: 1368076
microseconds
Time taken to sort 31000 employees using Bubble sort: 1331341
microseconds
Time taken to sort 31000 employees using Merge sort: 19446 microseconds
Time taken to sort 31000 employees using Quick sort: 7876672 microseconds
14 Assignment 2 : Quick sort, Merge sort, Bubble Sort, Selection Sort and Insertion sort Comparison.

Code while ((j > 0) &&


(employees[j - 1].salary >
employees[j].salary)) {
#include <iostream> swap(employees[j],
#include <string> employees[j - 1]);
#include <cstdlib> j = j - 1;
#include <ctime> }
#include <chrono> }
#include <fstream> }

using namespace std; void selectionSort(Employee*


using namespace std::chrono; employees, int n) {
for (int i = 0; i < n - 1;
struct Employee { i++) {
string name; int minIndex = i;
int salary; for (int j = i + 1; j <
}; n; j++) {
if
void (employees[j].salary <
generateEmployees(Employee* employees[minIndex].salary) {
employees, int n) { minIndex = j;
string firstNames[] = { }
"Mubashir", "Huzaifah", }
"Ibrahim", "Anas", "Fahad", swap(employees[i],
"Raja", "Uzair", "Hasnain", employees[minIndex]);
"Ammar", "Raheem" }; }
string lastNames[] = { }
"Sajid", "Ibrahim", "Shahid",
"Zohrab", "Saghir", "Khan", // Function to bubbleSort
"Arshad", "Khan", "Sadiq", Algorithim
"Shamim" }; void bubbleSort(string
nameArray[], int salaryArray[],
srand(time(NULL)); int n)
{
for (int i = 0; i < n; i++) for (int i = 0; i < n - 1;
{ ++i)
employees[i].name = {
firstNames[rand() % 10] + " " + for (int j = 0; j < n -
lastNames[rand() % 10]; i - 1; ++j)
employees[i].salary = {
rand() % 100000 + 50000; if (salaryArray[j]
} > salaryArray[j + 1])
} {

void insertionSort(Employee* swap(salaryArray[j],


employees, int n) { salaryArray[j + 1]);
for (int i = 1; i < n; i++)
{ swap(nameArray[j], nameArray[j
int j = i; + 1]);
}
}
15 Assignment 2 : Quick sort, Merge sort, Bubble Sort, Selection Sort and Insertion sort Comparison.

} names[k] =
} R_names[j];
void merge(double salaries[], j++;
string names[], int left, int }
mid, int right) { k++;
int n1 = mid - left + 1; }
int n2 = right - mid;
// Copy the remaining
// Create temporary arrays elements of L and R back into
for left and right partitions the original arrays
double* L_salaries = new while (i < n1) {
double[n1]; salaries[k] =
double* R_salaries = new L_salaries[i];
double[n2]; names[k] = L_names[i];
string* L_names = new i++;
string[n1]; k++;
string* R_names = new }
string[n2]; while (j < n2) {
salaries[k] =
// Copy data to temporary R_salaries[j];
arrays names[k] = R_names[j];
for (int i = 0; i < n1; j++;
i++) { k++;
L_salaries[i] = }
salaries[left + i];
L_names[i] = names[left // Free memory used by
+ i]; temporary arrays
} delete[] L_salaries;
for (int j = 0; j < n2; delete[] R_salaries;
j++) { delete[] L_names;
R_salaries[j] = delete[] R_names;
salaries[mid + 1 + j]; }
R_names[j] = names[mid
+ 1 + j]; // Mergesort algorithm for
} sorting salaries and names in
parallel
// Merge the temporary void mergesort(double
arrays back into the original salaries[], string names[], int
arrays left, int right) {
int i = 0, j = 0, k = left; if (left >= right) {
while (i < n1 && j < n2) { return; // base case:
if (L_salaries[i] <= nothing to sort
R_salaries[j]) { }
salaries[k] = int mid = left + (right -
L_salaries[i]; left) / 2;
names[k] = mergesort(salaries, names,
L_names[i]; left, mid);
i++; mergesort(salaries, names,
} mid + 1, right);
else { merge(salaries, names,
salaries[k] = left, mid, right);
R_salaries[j]; }
16 Assignment 2 : Quick sort, Merge sort, Bubble Sort, Selection Sort and Insertion sort Comparison.

//vary array size from 1000


// Partition function for to 10000
quicksort algorithm for (int nfor = 1000; nfor
int partition(double < 100000; nfor = nfor + 10000)
salaries[], string nameS[], int {
low, int high) { const int NUM_EMPLOYEES
double pivot = = nfor;
salaries[high]; Employee
int i = low - 1; employees[NUM_EMPLOYEES];
for (int j = low; j < high;
j++) { generateEmployees(employees,
if (salaries[j] < NUM_EMPLOYEES);
pivot) {
i++; // Start timer for
swap(salaries[i], insertion sort
salaries[j]);
swap(nameS[i], high_resolution_clock::time_poi
nameS[j]); nt t1 =
} high_resolution_clock::now();
}
swap(salaries[i + 1], insertionSort(employees,
salaries[high]); NUM_EMPLOYEES);
swap(nameS[i + 1],
nameS[high]); high_resolution_clock::time_poi
nt t2 =
return i + 1; high_resolution_clock::now();
} auto durationInsertion
=
// Quicksort algorithm for duration_cast<microseconds>(t2
sorting salaries and names in - t1).count();
parallel
void quicksort(double // Start timer for
salaries[], string nameS[], int selection sort
low, int high) { t1 =
if (low < high) { high_resolution_clock::now();
// Partition the arrays
int pivot_index = selectionSort(employees,
partition(salaries, nameS, low, NUM_EMPLOYEES);
high); t2 =
high_resolution_clock::now();
// Sort the partitions auto durationSelection
recursively =
quicksort(salaries, duration_cast<microseconds>(t2
nameS, low, pivot_index - 1); - t1).count();
quicksort(salaries,
nameS, pivot_index + 1, high); string
} namesBubbleSort[NUM_EMPLOYEES];
} int
salariesBubbleSort[NUM_EMPLOYEE
S];
int main() { for (int i = 0; i <
NUM_EMPLOYEES; i++) {
17 Assignment 2 : Quick sort, Merge sort, Bubble Sort, Selection Sort and Insertion sort Comparison.

namesBubbleSort[i]
= employees[i].name; // Copy salaries and
names arrays for quicksort
salariesBubbleSort[i] = double
employees[i].salary; salariesQuickSort[NUM_EMPLOYEES
} ];
string
// Start timer for namesQuickSort[NUM_EMPLOYEES];
bubble sort for (int i = 0; i <
t1 = NUM_EMPLOYEES; i++) {
high_resolution_clock::now();
salariesQuickSort[i] =
bubbleSort(namesBubbleSort, employees[i].salary;
salariesBubbleSort, namesQuickSort[i] =
NUM_EMPLOYEES); employees[i].name;
t2 = }
high_resolution_clock::now();
auto durationBubble = // Start timer for
duration_cast<microseconds>(t2 quicksort
- t1).count(); t1 =
high_resolution_clock::now();
double
salariesMergeSort[NUM_EMPLOYEES quicksort(salariesQuickSort,
]; namesQuickSort, 0,
string NUM_EMPLOYEES - 1);
namesMergeSort[NUM_EMPLOYEES]; t2 =
for (int i = 0; i < high_resolution_clock::now();
NUM_EMPLOYEES; i++) { auto durationQuickSort
namesMergeSort[i] = =
employees[i].name; duration_cast<microseconds>(t2
- t1).count();
salariesMergeSort[i] =
employees[i].salary;
}

// Start timer for // Log time taken to


merge sort file
ofstream
high_resolution_clock::time_poi logFile("sortLog.txt",
nt s1 = ios::app);
high_resolution_clock::now(); logFile << "Time taken
to sort " << NUM_EMPLOYEES << "
mergesort(salariesMergeSort, employees using insertion sort:
namesMergeSort, 0, " << durationInsertion << "
NUM_EMPLOYEES - 1); microseconds" << endl;
logFile << "Time taken
high_resolution_clock::time_poi to sort " << NUM_EMPLOYEES << "
nt s2 = employees using selection sort:
high_resolution_clock::now(); " << durationSelection << "
auto durationMerge = microseconds" << endl;
duration_cast<microseconds>(s2 logFile << "Time taken
- s1).count(); to sort " << NUM_EMPLOYEES << "
18 Assignment 2 : Quick sort, Merge sort, Bubble Sort, Selection Sort and Insertion sort Comparison.

employees using Bubble sort: " logFile << "Time taken


<< durationBubble << " to sort " << NUM_EMPLOYEES << "
microseconds" << endl; employees using Quick sort: "
logFile << "Time taken << durationQuickSort << "
to sort " << NUM_EMPLOYEES << " microseconds" << endl;
employees using Merge sort: " }
<< durationMerge << " return 0;
microseconds" << endl; }

You might also like