Quick sorting:
Copy codeThe Code is as follows: namespace QuickSort
{
Class QuickSort
{
Public static void Sort (int [] array)
{
DoSort (array, 0, array. Length-1 );
}
Private static void DoSort (int [] array, int start, int end)
{
If (start <end)
{
Int temp = Partition (array, start, end );
DoSort (array, start, temp-1 );
DoSort (array, temp + 1, end );
}
}
Private static int Partition (int [] array, int start, int end)
{
Int index = start-1;
For (var I = start; I <end; I ++)
{
If (array [I] <array [end])
{
Index ++;
Swap (array, index, I );
}
}
Swap (array, index + 1, end );
Return index + 1;
}
Private static void Swap (int [] array, int index1, int index2)
{
Var temp = array [index1];
Array [index1] = array [index2];
Array [index2] = temp;
}
}
}
The above is the code for fast sorting. There are two important methods:
1. Partition: This method divides an array into three areas by taking an element of an array as a reference element (axis element or main element:
[<= Reference element] [Reference element] [> = reference element]
2. DoSort: This method will call Partition to Partition the array, and recursively call the new Child array to achieve the goal of order.
The code above uses the last element of the array as the reference element, which is only one of the methods for selecting the reference element. We can also select an array element or an element in the middle of the array as a reference element. In fact, the selection of reference elements has a great impact on the performance of quick sorting. If the selected reference element can divide the array into relatively balanced areas, fast sorting will become the fastest sorting algorithm. However, in another extreme situation, each split array is in the relationship between 1 and n-1, and the fast sorting will become very slow. The specific performance data will be discussed later.