Skip to content

Commit 15f90c0

Browse files
author
Joshua Scott
authored
Added quicksort, improved counting
* Implemented quicksort (including counting and printing updates) * Improved the counting system (fewer variables, cleaner code) Next steps: * Add mergesort * Add an ascending/descending option * Add option to set options through console
1 parent 5fcb0f5 commit 15f90c0

File tree

1 file changed

+127
-69
lines changed

1 file changed

+127
-69
lines changed

compare-sorting-algorithms.cs

Lines changed: 127 additions & 69 deletions
Original file line numberDiff line numberDiff line change
@@ -8,55 +8,45 @@ class Program
88
const string a = "ascending";
99
const string d = "descending";
1010
const string r = "random";
11-
11+
1212
const string B = "Bubble";
1313
const string S = "Selection";
1414
const string I = "Insertion";
15+
const string Q = "Quick";
1516
const string A = "All";
1617

1718
// Variables required to count the number of operations
1819
// Unsigned longs used in all cases to be safe and avoid casting, though not required for all
1920
// Bubble:
20-
static ulong countComparisonsBubble = 0;
2121
static ulong totalComparisonsBubble = 0;
22-
static ulong averageComparisonsBubble = 0;
23-
static ulong countSwapsBubble = 0;
2422
static ulong totalSwapsBubble = 0;
25-
static ulong averageSwapsBubble = 0;
2623
// Selection:
27-
static ulong countComparisonsSelection = 0;
2824
static ulong totalComparisonsSelection = 0;
29-
static ulong averageComparisonsSelection = 0;
30-
static ulong countSwapsSelection = 0;
3125
static ulong totalSwapsSelection = 0;
32-
static ulong averageSwapsSelection = 0;
3326
// Insertion:
34-
static ulong countComparisonsInsertion = 0;
3527
static ulong totalComparisonsInsertion = 0;
36-
static ulong averageComparisonsInsertion = 0;
37-
static ulong countShuffles;
3828
static ulong totalShuffles = 0;
39-
static ulong averageShuffles = 0;
40-
static ulong countInsertions = 0;
4129
static ulong totalInsertions = 0;
42-
static ulong averageInsertions = 0;
30+
//Quick:
31+
static ulong totalComparisonsQuick = 0;
32+
static ulong totalSwapsQuick = 0;
4333

4434
static void Main(string[] args)
4535
{
4636
/*
4737
* Edit these variables to set up!
4838
*/
49-
string sortingAlgorithm = A; // B/S/I/A
39+
string sortingAlgorithm = A; // B/S/I/Q/A
5040
string orderOfArray = r; // a/d/r
51-
ulong numberOfSorts = 10;
52-
int lengthOfArray = 10;
41+
ulong numberOfSorts = 1;
42+
int lengthOfArray = 50;
5343
bool printUpdates = true;
54-
55-
Console.WriteLine("Sorting algorithm: {0}\nResults of {1} passes of {2}-int {3} arrays:\n",
44+
45+
Console.WriteLine("Sorting algorithm: {0}\nResults of {1} passes of {2}-int {3} arrays:\n",
5646
sortingAlgorithm, numberOfSorts, lengthOfArray, orderOfArray);
57-
47+
5848
/* Initialise specified number of arrays of ints
59-
* Pass each one to Bubble||Selection||Insertion sort
49+
* Pass each one to Bubble||Selection||Insertion||Quick sort
6050
* Count total number of comparisons/swaps/shuffles/insertions as required
6151
*/
6252
for (int i = 0; i < (int)numberOfSorts; i++)
@@ -67,50 +57,37 @@ static void Main(string[] args)
6757
// Create array
6858
int[] array = MakeArray(lengthOfArray, orderOfArray);
6959

70-
// Call Bubble||Selection||Insertion sort, and add correct variables
60+
// Call Bubble||Selection||Insertion||Quick sort, and add correct variables
7161
if (sortingAlgorithm == B)
72-
{
73-
BubbleSort(array, printUpdates, out countComparisonsBubble, out countSwapsBubble);
74-
totalComparisonsBubble += countComparisonsBubble;
75-
totalSwapsBubble += countSwapsBubble;
76-
}
62+
BubbleSort(array, printUpdates);
7763
else if (sortingAlgorithm == S)
78-
{
79-
SelectionSort(array, printUpdates, out countComparisonsSelection, out countSwapsSelection);
80-
totalComparisonsSelection += countComparisonsSelection;
81-
totalSwapsSelection += countSwapsSelection;
82-
}
64+
SelectionSort(array, printUpdates);
8365
else if (sortingAlgorithm == I)
84-
{
85-
InsertionSort(array, printUpdates, out countComparisonsInsertion, out countShuffles, out countInsertions);
86-
totalComparisonsInsertion += countComparisonsInsertion;
87-
totalShuffles += countShuffles;
88-
totalInsertions += countInsertions;
89-
}
90-
else if (sortingAlgorithm == A)
66+
InsertionSort(array, printUpdates);
67+
else if (sortingAlgorithm == Q)
68+
QuickSort(array, 0, array.Length - 1, printUpdates);
69+
else if (sortingAlgorithm == A)
9170
{
9271
// Copy each array (since they're arrays of ints, shallow copy is enough)
9372
int[] array1 = (int[])array.Clone();
9473
int[] array2 = (int[])array.Clone();
74+
int[] array3 = (int[])array.Clone();
9575

9676
if (printUpdates)
9777
Console.WriteLine("Bubble sort:");
98-
BubbleSort(array, printUpdates, out countComparisonsBubble, out countSwapsBubble);
99-
totalComparisonsBubble += countComparisonsBubble;
100-
totalSwapsBubble += countSwapsBubble;
78+
BubbleSort(array, printUpdates);
10179

10280
if (printUpdates)
10381
Console.WriteLine("\nSelection sort:");
104-
SelectionSort(array1, printUpdates, out countComparisonsSelection, out countSwapsSelection);
105-
totalComparisonsSelection += countComparisonsSelection;
106-
totalSwapsSelection += countSwapsSelection;
82+
SelectionSort(array1, printUpdates);
10783

10884
if (printUpdates)
10985
Console.WriteLine("\nInsertion sort:");
110-
InsertionSort(array2, printUpdates, out countComparisonsInsertion, out countShuffles, out countInsertions);
111-
totalComparisonsInsertion += countComparisonsInsertion;
112-
totalShuffles += countShuffles;
113-
totalInsertions += countInsertions;
86+
InsertionSort(array2, printUpdates);
87+
88+
if (printUpdates)
89+
Console.WriteLine("\nQuick sort:");
90+
QuickSort(array3, 0, array3.Length - 1, printUpdates);
11491

11592
if (printUpdates)
11693
Console.WriteLine();
@@ -164,7 +141,7 @@ private static int[] MakeArray(int length, string orderOfArray)
164141
* and distinguishes between 'sorted' and 'unsorted' parts.
165142
* Time complexity: Worst = n^2, Best = n, Average = n^2.
166143
*/
167-
private static int[] BubbleSort(int[] array, bool printUpdates, out ulong countComparisonsBubble, out ulong countSwapsBubble)
144+
private static int[] BubbleSort(int[] array, bool printUpdates)
168145
{
169146
if (printUpdates)
170147
PrintArray(array, "initial array");
@@ -223,8 +200,8 @@ private static int[] BubbleSort(int[] array, bool printUpdates, out ulong countC
223200
"\nNumber of swaps: " + swaps);
224201
}
225202

226-
countComparisonsBubble = comparisons;
227-
countSwapsBubble = swaps;
203+
totalComparisonsBubble += comparisons;
204+
totalSwapsBubble += swaps;
228205
return array;
229206
}
230207

@@ -233,7 +210,7 @@ private static int[] BubbleSort(int[] array, bool printUpdates, out ulong countC
233210
* Doesn't redundantly swap the last remaining element with itself.
234211
* Time complexity: Worst = n^2, Best = n^2, Average = n^2.
235212
*/
236-
private static int[] SelectionSort(int[] array, bool printUpdates, out ulong countComparisonsSelection, out ulong countSwapsSelection)
213+
private static int[] SelectionSort(int[] array, bool printUpdates)
237214
{
238215
if (printUpdates)
239216
PrintArray(array, "initial array");
@@ -257,7 +234,7 @@ private static int[] SelectionSort(int[] array, bool printUpdates, out ulong cou
257234
// Since the next line will compare elements, add 1 to comparisons
258235
comparisons++;
259236
if (printUpdates)
260-
Console.WriteLine("^ Compare " + min.ToString().PadLeft(2) +
237+
Console.WriteLine("^ Compare " + min.ToString().PadLeft(2) +
261238
" with " + array[currentIndex].ToString().PadLeft(2));
262239
if (array[currentIndex] < min)
263240
{
@@ -287,8 +264,8 @@ private static int[] SelectionSort(int[] array, bool printUpdates, out ulong cou
287264
"\nNumber of swaps: " + swaps);
288265
}
289266

290-
countComparisonsSelection = comparisons;
291-
countSwapsSelection = swaps;
267+
totalComparisonsSelection += comparisons;
268+
totalSwapsSelection += swaps;
292269
return array;
293270
}
294271

@@ -297,7 +274,7 @@ private static int[] SelectionSort(int[] array, bool printUpdates, out ulong cou
297274
* At the end, prints a summary of the number of comparisons, shuffles, and insertions.
298275
* Time complexity: Worst = n^2, Best = n, Average = n^2.
299276
*/
300-
private static int[] InsertionSort(int[] array, bool printUpdates, out ulong countComparisonsInsertion, out ulong countShuffles, out ulong countInsertions)
277+
private static int[] InsertionSort(int[] array, bool printUpdates)
301278
{
302279
if (printUpdates)
303280
PrintArray(array, "initial array");
@@ -349,7 +326,7 @@ private static int[] InsertionSort(int[] array, bool printUpdates, out ulong cou
349326
}
350327
}
351328

352-
if(printUpdates && !endReached)
329+
if (printUpdates && !endReached)
353330
{
354331
Console.WriteLine(", it's not smaller so we insert {0} here:", currentElement.ToString().PadLeft(2));
355332
}
@@ -376,12 +353,84 @@ private static int[] InsertionSort(int[] array, bool printUpdates, out ulong cou
376353
"\nNumber of insertions: " + insertions);
377354
}
378355

379-
countComparisonsInsertion = comparisons;
380-
countShuffles = shuffles;
381-
countInsertions = insertions;
356+
totalComparisonsInsertion += comparisons;
357+
totalShuffles += shuffles;
358+
totalInsertions += insertions;
382359
return array;
383360
}
384361

362+
/* Sorts an array using Quick sort algorithm, along with Partition().
363+
* Calls Partition(), then makes recursive calls on the left and right of partitionIndex
364+
* Time complexity: Worst = n^2, Best = n logn, Average = n logn.
365+
*/
366+
private static void QuickSort(int[] array, int start, int end, bool printUpdates)
367+
{
368+
if (start == 0 && end == array.Length - 1 && printUpdates)
369+
PrintArray(array, "initial array");
370+
371+
// Base case
372+
if (start >= end)
373+
{
374+
if (printUpdates)
375+
Console.WriteLine(" Base case reached");
376+
return;
377+
}
378+
379+
// Call for partition
380+
int partitionIndex = Partition(array, start, end, printUpdates);
381+
// Left side recursive call
382+
if (printUpdates)
383+
Console.WriteLine("Recursive call on left side, from index {0} to {1}:", start, partitionIndex - 1);
384+
QuickSort(array, start, partitionIndex - 1, printUpdates);
385+
// Right side recursive call
386+
if (printUpdates)
387+
Console.WriteLine("Recursive call on right side, from index {0} to {1}:", partitionIndex + 1, end);
388+
QuickSort(array, partitionIndex + 1, end, printUpdates);
389+
}
390+
391+
/* Sets pivot to the last element in given array, and partitionIndex to the first.
392+
* Iterates through each element and compares against the pivot.
393+
* If it's less than or equal to the pivot, swap it with partitionIndex++.
394+
* If it's greater than pivot, leave it alone.
395+
* Finally, swap the pivot with the partitionIndex.
396+
* Now, all elements <= pivot are on its left, and elements > pivot are on the right.
397+
*/
398+
private static int Partition(int[] array, int start, int end, bool printUpdates)
399+
{
400+
ulong comparisons = 0;
401+
ulong swaps = 0;
402+
403+
// Set pivot to end and partitionIndex to start
404+
int pivot = array[end];
405+
int partitionIndex = start;
406+
if (printUpdates)
407+
Console.WriteLine("Pivot is {0}, move <= elements to left and > to right", pivot);
408+
409+
// Iterate from start to end
410+
for (int i = start; i < end; i++)
411+
{
412+
// Compare each element to the pivot
413+
comparisons++;
414+
if (array[i] <= pivot)
415+
{
416+
// If it's <= pivot, swap to left of partition
417+
Swap(array, i, partitionIndex);
418+
partitionIndex++;
419+
swaps++;
420+
}
421+
}
422+
423+
// Move the pivot to the partition. Now, elements left are <= pivot, right are > pivot
424+
Swap(array, end, partitionIndex);
425+
swaps++;
426+
427+
totalComparisonsQuick += comparisons;
428+
totalSwapsQuick += swaps;
429+
430+
PrintArray(array, "Pivot moved to index " + partitionIndex.ToString().PadLeft(2));
431+
return partitionIndex;
432+
}
433+
385434
// Prints the current array with a message to describe the situation
386435
private static void PrintArray(int[] array, string text)
387436
{
@@ -407,33 +456,42 @@ private static void DisplayResults(string sortingAlgorithm, ulong numberOfSorts,
407456

408457
if (sortingAlgorithm == "Bubble" || sortingAlgorithm == "All")
409458
{
410-
averageComparisonsBubble = totalComparisonsBubble / numberOfSorts;
411-
averageSwapsBubble = totalSwapsBubble / numberOfSorts;
459+
ulong averageComparisonsBubble = totalComparisonsBubble / numberOfSorts;
460+
ulong averageSwapsBubble = totalSwapsBubble / numberOfSorts;
412461
if (sortingAlgorithm == "All")
413462
Console.WriteLine("Bubble sort results:\n");
414463
Console.WriteLine("Total comparisons: {0}\nAverage comparisons: {1}\n", totalComparisonsBubble, averageComparisonsBubble);
415464
Console.WriteLine("Total swaps: {0}\nAverage swaps: {1}\n", totalSwapsBubble, averageSwapsBubble);
416465
}
417466
if (sortingAlgorithm == "Selection" || sortingAlgorithm == "All")
418467
{
419-
averageComparisonsSelection = totalComparisonsSelection / numberOfSorts;
420-
averageSwapsSelection = totalSwapsSelection / numberOfSorts;
468+
ulong averageComparisonsSelection = totalComparisonsSelection / numberOfSorts;
469+
ulong averageSwapsSelection = totalSwapsSelection / numberOfSorts;
421470
if (sortingAlgorithm == "All")
422471
Console.WriteLine("Selection sort results:\n");
423472
Console.WriteLine("Total comparisons: {0}\nAverage comparisons: {1}\n", totalComparisonsSelection, averageComparisonsSelection);
424473
Console.WriteLine("Total swaps: {0}\nAverage swaps: {1}\n", totalSwapsSelection, averageSwapsSelection);
425474
}
426475
if (sortingAlgorithm == "Insertion" || sortingAlgorithm == "All")
427476
{
428-
averageComparisonsInsertion = totalComparisonsInsertion / numberOfSorts;
429-
averageShuffles = totalShuffles / numberOfSorts;
430-
averageInsertions = totalInsertions / numberOfSorts;
477+
ulong averageComparisonsInsertion = totalComparisonsInsertion / numberOfSorts;
478+
ulong averageShuffles = totalShuffles / numberOfSorts;
479+
ulong averageInsertions = totalInsertions / numberOfSorts;
431480
if (sortingAlgorithm == "All")
432481
Console.WriteLine("Insertion sort results:\n");
433482
Console.WriteLine("Total comparisons: {0}\nAverage comparisons: {1}\n", totalComparisonsInsertion, averageComparisonsInsertion);
434483
Console.WriteLine("Total shuffles: {0}\nAverage shuffles: {1}\n", totalShuffles, averageShuffles);
435484
Console.WriteLine("Total insertions: {0}\nAverage insertions: {1}\n", totalInsertions, averageInsertions);
436485
}
486+
if (sortingAlgorithm == "Quick" || sortingAlgorithm == "All")
487+
{
488+
ulong averageComparisonsQuick = totalComparisonsQuick / numberOfSorts;
489+
ulong averageSwapsQuick = totalSwapsQuick / numberOfSorts;
490+
if (sortingAlgorithm == "All")
491+
Console.WriteLine("Quick sort results:\n");
492+
Console.WriteLine("Total comparisons: {0}\nAverage comparisons: {1}\n", totalComparisonsQuick, averageComparisonsQuick);
493+
Console.WriteLine("Total swaps: {0}\nAverage swaps: {1}\n", totalSwapsQuick, averageSwapsQuick);
494+
}
437495
}
438496
}
439497
}

0 commit comments

Comments
 (0)