For my CS minor I was assigned to implement the Quicksort algorithm in C#. I gave it a go and found that I like the implementation of the algorithm more than Mergesort. Now that I've got my Quicksort implementation running, I'm very curious about what optimizations could be done.
using System.Collections.Generic;
namespace Assignment
{
public class QuickSort
{
public void Sort(List<int> list)
{
if (list.Count <= 1)
{
return;
}
int pivot = MedianOfThree(list);
int equalElementCount = 0;
List<int> smaller = new List<int>();
List<int> bigger = new List<int>();
for (int i = 0; i < list.Count; i++)
{
if (list[i] == pivot)
{
equalElementCount++;
}
else if (list[i] < pivot)
{
smaller.Add(list[i]);
}
else
{
bigger.Add(list[i]);
}
}
Sort(smaller);
Sort(bigger);
int pointer = 0;
for (int i = 0; i < smaller.Count; i++)
{
list[pointer++] = smaller[i];
}
for (int i = 0; i < equalElementCount; i++)
{
list[pointer++] = pivot;
}
for (int i = 0; i < bigger.Count; i++)
{
list[pointer++] = bigger[i];
}
}
private int MedianOfThree(List<int> list)
{
int firstElement = list[0];
int middleElement = list[list.Count / 2];
int lastElement = list[list.Count - 1];
if ((firstElement > middleElement) != (firstElement > lastElement))
{
return firstElement;
}
else if ((middleElement > firstElement) != (middleElement > lastElement))
{
return middleElement;
}
else
{
return lastElement;
}
}
}
}