1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
|
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
// Insertion sort sorting function it will take array and its size an argument
void insertionSort(int nums[], int m, int& comparisonsCount)
{
int j, val, i;
for (j = 1; j < m; j++)
{
val = nums[j];
i = j - 1;
comparisonsCount++;
while (i >= 0 && nums[i] > val)
{
comparisonsCount++;
nums[i + 1] = nums[i];
i = i - 1;
}
nums[i + 1] = val;
}
}
// Merge sort sorting function
void merge(int nums[], int left, int middle, int right, int& comparisonsCount)
{
int m1 = middle - left + 1;
int m2 = right - middle;
//int L[m1], R[m2];
int L[10000] {}, R[10000] {}; // TO GET TO COMPILE. TO CHANGE
for (int j = 0; j < m1; j++)
L[j] = nums[left + j];
for (int i = 0; i < m2; i++)
R[i] = nums[middle + 1 + i];
int j = 0;
int i = 0;
int s = left;
while (j < m1 && i < m2) {
if (L[j] <= R[i]) {
comparisonsCount++;
nums[s] = L[j];
j++;
} else {
nums[s] = R[i];
i++;
}
s++;
}
while (j < m1) {
nums[s] = L[j];
j++;
s++;
}
while (i < m2) {
nums[s] = R[i];
i++;
s++;
}
}
void mergeSort(int nums[], int left, int right, int& comparisonsCount) {
if (left >= right) {
return;//returns recursively
}
int middle = left + (right - left) / 2;
mergeSort(nums, left, middle, comparisonsCount);
mergeSort(nums, middle + 1, right, comparisonsCount);
merge(nums, left, middle, right, comparisonsCount);
}
//main function
int main()
{
srand(time(0));
int arr_1[1000]; int copy_arr1[1000];
int arr_2[10000]; int copy_arr2[10000];
for (int j = 0; j < 1000; j++)
{
arr_1[j] = rand();
copy_arr1[j] = arr_1[j];
}
int count_insertion = 0;
int count_merge = 0;
insertionSort(arr_1, 1000, count_insertion);
mergeSort(copy_arr1, 0, 1000 - 1, count_merge);
cout << "For 1000 length array: \n";
cout << "Comparision made for insertion sort: " << count_insertion;
cout << "\nComparision made of merge sort : " << count_merge;
for (int j = 0; j < 10000; j++)
{
arr_2[j] = rand();
copy_arr2[j] = arr_1[j];
}
count_insertion = 0;
count_merge = 0;
insertionSort(arr_2, 10000, count_insertion);
mergeSort(copy_arr2, 0, 10000 - 1, count_merge);
cout << "\n\nFor 10000 length array: \n";
cout << "Comparision made for insertion sort: " << count_insertion;
cout << "\nComparision made of merge sort : " << count_merge;
}
|