Just for fun I built a quicksort implementation in C# with Linq:
public static IEnumerable<T> quicksort<T>(IEnumerable<T> input) where T : IComparable<T>{
if (input.Count() <= 1) return input;
var pivot = input.FirstOrDefault();
var lesser = quicksort(input.Skip(1).Where(i => i.CompareTo(pivot) <= 0));
var greater = quicksort(input.Where(i => i.CompareTo(pivot) > 0));
return lesser.Append(pivot).Concat(greater);
}
It sorts 10000 random integers in about 13 seconds.
Changing it to use int[] instead of List results in about 700 times better performance! It only takes 21ms to sort the same 10000 random integers.
public static T[] quicksortArray<T>(T[] input) where T : IComparable<T>{
if (input.Count() <= 1) return input;
var pivot = input.FirstOrDefault();
var lesser = quicksortArray(input.Skip(1).Where(i => i.CompareTo(pivot) <= 0).ToArray());
var greater = quicksortArray(input.Where(i => i.CompareTo(pivot) > 0).ToArray());
return lesser.Append(pivot).Concat(greater).ToArray();
}
Just looking at the code I would have assumed this would have worse performance. I assumed that .ToArray() would create an additional array in memory and copy all integers there. I think passing an array vs. passing a list should take about the same time.
So where does this huge performance difference come from?
quicksortArray
toArray.Sort
too