Choose an index named middleIndex between fist Index and last index of an array which is to be sort.We can get a rearranged array that has the following jfeatures: all elements from first index to middle index is smaller than array[middleindex];all elements from middle index to last index is larger than array[middleindex].The Partition method return the middle index so we can rearrange the two subarray by the same way.
Let’s show it.
private void Swap(Int32[] arr, Int32 firstIndex, Int32 secondIndex)
{
if (firstIndex < arr.Length && secondIndex < arr.Length)
{
Int32 temp = arr[firstIndex];
arr[firstIndex] = arr[secondIndex];
arr[secondIndex] = temp;
}
}
// In this method,we use arr[lastIndex] as the middleValue
private Int32 Partition(Int32[] arr, Int32 firstIndex, Int32 lastIndex)
{
if (firstIndex < arr.Length && lastIndex < arr.Length)
{
Int32 middleValue = arr[lastIndex];
Int32 i = firstIndex - 1;
for (Int32 j = firstIndex; j < lastIndex; j++)
{
if (arr[j] <= middleValue)
Swap(arr, ++i, j);
}
Swap(arr, i + 1, lastIndex);
return i + 1;
}
else
{
return -1;
}
}
public void Sort(Int32[] arr, Int32 firstIndex, Int32 lastIndex)
{
if (firstIndex < lastIndex)
{
Int32 middleIndex = Partition(arr, firstIndex, lastIndex);
Sort(arr, firstIndex, middleIndex - 1);
Sort(arr, middleIndex + 1, lastIndex);
}
}
Ok,it fine.
Let's make a random index between firstIndex and lastIndex,Choose arr[randomIndex] as the middleValue
{
Random randomer = new Random();
Int32 index = randomer.Next(firstIndex, lastIndex);
Swap(arr, index, lastIndex);
return Partition(arr, firstIndex, lastIndex);
}
public void RandomizedSort(Int32[] arr, Int32 firstIndex, Int32 lastIndex)
{
if (firstIndex < lastIndex)
{
Int32 middleIndex = RandomizedPartition(arr, firstIndex, lastIndex);
RandomizedSort(arr, firstIndex, middleIndex - 1);
RandomizedSort(arr, middleIndex + 1, lastIndex);
}
}
the worst-case running time of QuickSort is big theta n*n on an input array of n numbers.
But the quicksort is often the best practical choice for sorting because it is efficient in the average:its expected running time is big theta n*lgn.