QuickSort - C#
Join the DZone community and get the full member experience.
Join For FreeQuickSort - C#
Efficiency: O(nlog n)
public static int[] QuickSort(int[] arr)
{
if (arr.Length <= 1)
return arr;
int pivot = arr.Length - 1;
int[] less = GetLessThanEqualToPivot(arr, pivot);
int[] greater = GetGreaterThanPivot(arr, pivot);
return Concatenate(QuickSort(less), arr[pivot], QuickSort(greater));
}
public static int[] Concatenate(int[] less, int pivotElement, int[] greater)
{
List _result = new List();
_result.AddRange(less);
_result.Add(pivotElement);
_result.AddRange(greater);
return _result.ToArray();
}
public static int[] GetLessThanEqualToPivot(int[] arr, int pivot)
{
List _result = new List();
for (int i = 0; i < arr.Length - 1; i++)
{
if (arr[i] <= arr[pivot])
{
_result.Add(arr[i]);
}
}
return _result.ToArray();
}
public static int[] GetGreaterThanPivot(int[] arr, int pivot)
{
List _result = new List();
for (int i = 0; i < arr.Length - 1; i++)
{
if (arr[i] > arr[pivot])
{
_result.Add(arr[i]);
}
}
return _result.ToArray();
}
Efficiency (statistics)
Opinions expressed by DZone contributors are their own.
Comments