Skip to content

Commit 63fd8d3

Browse files
committed
Added Mergesort and minor changes
* Implemented Mergesort, including ability to count comparisons and swaps for it. * Changed how printing initial arrays works (now it's always handled when the sorting method is called, instead of inside the methods which involved a convoluted if-check for recursive algorithms) * Namespace changed to 'CompareSorts'
1 parent 15f90c0 commit 63fd8d3

File tree

1 file changed

+119
-18
lines changed

1 file changed

+119
-18
lines changed

compare-sorting-algorithms.cs

Lines changed: 119 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
using System;
22
using System.Threading.Tasks;
33

4-
namespace PsetS3
4+
namespace CompareSorts
55
{
66
class Program
77
{
@@ -13,6 +13,7 @@ class Program
1313
const string S = "Selection";
1414
const string I = "Insertion";
1515
const string Q = "Quick";
16+
const string M = "Merge";
1617
const string A = "All";
1718

1819
// Variables required to count the number of operations
@@ -30,16 +31,19 @@ class Program
3031
//Quick:
3132
static ulong totalComparisonsQuick = 0;
3233
static ulong totalSwapsQuick = 0;
34+
//Merge:
35+
static ulong totalComparisonsMerge = 0;
36+
static ulong totalSwapsMerge = 0;
3337

3438
static void Main(string[] args)
3539
{
3640
/*
3741
* Edit these variables to set up!
3842
*/
39-
string sortingAlgorithm = A; // B/S/I/Q/A
43+
string sortingAlgorithm = A; // B/S/I/Q/M/A
4044
string orderOfArray = r; // a/d/r
4145
ulong numberOfSorts = 1;
42-
int lengthOfArray = 50;
46+
int lengthOfArray = 10;
4347
bool printUpdates = true;
4448

4549
Console.WriteLine("Sorting algorithm: {0}\nResults of {1} passes of {2}-int {3} arrays:\n",
@@ -57,7 +61,10 @@ static void Main(string[] args)
5761
// Create array
5862
int[] array = MakeArray(lengthOfArray, orderOfArray);
5963

60-
// Call Bubble||Selection||Insertion||Quick sort, and add correct variables
64+
if (printUpdates && sortingAlgorithm != A)
65+
PrintArray(array, "initial array");
66+
67+
// Call Bubble||Selection||Insertion||Quick||Merge sort, and add correct variables
6168
if (sortingAlgorithm == B)
6269
BubbleSort(array, printUpdates);
6370
else if (sortingAlgorithm == S)
@@ -66,29 +73,51 @@ static void Main(string[] args)
6673
InsertionSort(array, printUpdates);
6774
else if (sortingAlgorithm == Q)
6875
QuickSort(array, 0, array.Length - 1, printUpdates);
69-
else if (sortingAlgorithm == A)
76+
else if (sortingAlgorithm == M)
77+
MergeSort(array, printUpdates);
78+
else if (sortingAlgorithm == A)
7079
{
7180
// Copy each array (since they're arrays of ints, shallow copy is enough)
7281
int[] array1 = (int[])array.Clone();
7382
int[] array2 = (int[])array.Clone();
7483
int[] array3 = (int[])array.Clone();
84+
int[] array4 = (int[])array.Clone();
7585

7686
if (printUpdates)
77-
Console.WriteLine("Bubble sort:");
87+
{
88+
Console.WriteLine("\nBubble sort:");
89+
PrintArray(array, "initial array");
90+
}
7891
BubbleSort(array, printUpdates);
7992

8093
if (printUpdates)
94+
{
8195
Console.WriteLine("\nSelection sort:");
96+
PrintArray(array, "initial array");
97+
}
8298
SelectionSort(array1, printUpdates);
8399

84100
if (printUpdates)
101+
{
85102
Console.WriteLine("\nInsertion sort:");
103+
PrintArray(array, "initial array");
104+
}
86105
InsertionSort(array2, printUpdates);
87106

88107
if (printUpdates)
108+
{
89109
Console.WriteLine("\nQuick sort:");
110+
PrintArray(array, "initial array");
111+
}
90112
QuickSort(array3, 0, array3.Length - 1, printUpdates);
91113

114+
if (printUpdates)
115+
{
116+
Console.WriteLine("\nMerge sort:");
117+
PrintArray(array, "initial array");
118+
}
119+
MergeSort(array4, printUpdates);
120+
92121
if (printUpdates)
93122
Console.WriteLine();
94123
}
@@ -143,9 +172,6 @@ private static int[] MakeArray(int length, string orderOfArray)
143172
*/
144173
private static int[] BubbleSort(int[] array, bool printUpdates)
145174
{
146-
if (printUpdates)
147-
PrintArray(array, "initial array");
148-
149175
ulong comparisons = 0;
150176
ulong swaps = 0;
151177
// Get (length - 1) because we compare with (j + 1)
@@ -212,9 +238,6 @@ private static int[] BubbleSort(int[] array, bool printUpdates)
212238
*/
213239
private static int[] SelectionSort(int[] array, bool printUpdates)
214240
{
215-
if (printUpdates)
216-
PrintArray(array, "initial array");
217-
218241
ulong comparisons = 0;
219242
ulong swaps = 0;
220243
int n = array.Length;
@@ -276,9 +299,6 @@ private static int[] SelectionSort(int[] array, bool printUpdates)
276299
*/
277300
private static int[] InsertionSort(int[] array, bool printUpdates)
278301
{
279-
if (printUpdates)
280-
PrintArray(array, "initial array");
281-
282302
// Since elements aren't directly swapped, it doesn't make sense to count swaps like the other algorithms.
283303
// Instead, we count shuffles (when an element moves up one index)
284304
// and insertions (where the currentElement is inserted into its correct index for that pass)
@@ -365,9 +385,6 @@ private static int[] InsertionSort(int[] array, bool printUpdates)
365385
*/
366386
private static void QuickSort(int[] array, int start, int end, bool printUpdates)
367387
{
368-
if (start == 0 && end == array.Length - 1 && printUpdates)
369-
PrintArray(array, "initial array");
370-
371388
// Base case
372389
if (start >= end)
373390
{
@@ -431,6 +448,81 @@ private static int Partition(int[] array, int start, int end, bool printUpdates)
431448
return partitionIndex;
432449
}
433450

451+
private static void MergeSort(int[] array, bool printUpdates)
452+
{
453+
int n = array.Length;
454+
int mid = n/2;
455+
456+
// Base case
457+
if (n < 2)
458+
{
459+
if (printUpdates)
460+
Console.WriteLine(" Base case reached");
461+
return;
462+
}
463+
464+
// Split the array into two halves
465+
if (printUpdates)
466+
Console.WriteLine("Recursive call on left side, from index 0 to {0}:", mid - 1);
467+
int[] left = new int[mid];
468+
Array.Copy(array, 0, left, 0, mid);
469+
if (printUpdates)
470+
Console.WriteLine("Recursive call on right side, from index {0} to {1}:", mid, n - 1);
471+
int[] right = new int[n - mid];
472+
Array.Copy(array, mid, right, 0, n - mid);
473+
474+
//Recursive call to sort the two halves
475+
MergeSort(left, printUpdates);
476+
MergeSort(right, printUpdates);
477+
478+
// Call to merge the sorted halves into a sorted whole
479+
Merge(array, left, right, printUpdates);
480+
}
481+
482+
// Merges two sorted arrays into one sorted array
483+
private static void Merge(int[] array, int[] leftArray, int[] rightArray, bool printUpdates)
484+
{
485+
ulong comparisons = 0;
486+
ulong swaps = 0;
487+
488+
int leftCount = leftArray.Length;
489+
int rightCount = rightArray.Length;
490+
491+
int l = 0; // index of left sub-array
492+
int r = 0; // index of right sub-array
493+
int m = 0; // index of merged array
494+
495+
496+
// Copy the next value in left and right sub-arrays to the main array
497+
while (l < leftCount && r < rightCount)
498+
{
499+
comparisons++;
500+
swaps++;
501+
if (leftArray[l] < rightArray[r])
502+
array[m++] = leftArray[l++];
503+
else
504+
array[m++] = rightArray[r++];
505+
}
506+
// If end of right subarray reached first, copy remaining elements from left subarray
507+
while (l < leftCount)
508+
{
509+
swaps++;
510+
array[m++] = leftArray[l++];
511+
}
512+
// If end of left subarray reached first, copy remaining elements from right subarray
513+
while (r < rightCount)
514+
{
515+
swaps++;
516+
array[m++] = rightArray[r++];
517+
}
518+
519+
if (printUpdates)
520+
PrintArray(array, "<- After a completed Merge of two sub-arrays");
521+
522+
totalComparisonsMerge += comparisons;
523+
totalSwapsMerge += swaps;
524+
}
525+
434526
// Prints the current array with a message to describe the situation
435527
private static void PrintArray(int[] array, string text)
436528
{
@@ -492,6 +584,15 @@ private static void DisplayResults(string sortingAlgorithm, ulong numberOfSorts,
492584
Console.WriteLine("Total comparisons: {0}\nAverage comparisons: {1}\n", totalComparisonsQuick, averageComparisonsQuick);
493585
Console.WriteLine("Total swaps: {0}\nAverage swaps: {1}\n", totalSwapsQuick, averageSwapsQuick);
494586
}
587+
if (sortingAlgorithm == "Merge" || sortingAlgorithm == "All")
588+
{
589+
ulong averageComparisonsMerge = totalComparisonsMerge / numberOfSorts;
590+
ulong averageSwapsMerge = totalSwapsMerge / numberOfSorts;
591+
if (sortingAlgorithm == "All")
592+
Console.WriteLine("Merge sort results:\n");
593+
Console.WriteLine("Total comparisons: {0}\nAverage comparisons: {1}\n", totalComparisonsMerge, averageComparisonsMerge);
594+
Console.WriteLine("Total swaps: {0}\nAverage swaps: {1}\n", totalSwapsMerge, averageSwapsMerge);
595+
}
495596
}
496597
}
497598
}

0 commit comments

Comments
 (0)