Time Complexity Analysis for sorting
Each trip selects the smallest (or largest) element from the data elements to be sorted, and places the order at the beginning (last) of the sorted series ), until all data elements to be sorted are arranged. Selecting sorting is an unstable sorting method.
The sorting mode selects the smallest element for each position. For example, you can specify the smallest element for the first position, select the second smallest element for the second element in the remaining element, and so on, the n-th element does not need to be selected until the n-th element, because only one of its largest elements is left. If an element is smaller than the current element, and the small element appears after an element equal to the current element, then the stability will be damaged after the exchange. Compare interfaces. For example, in the sequence 5 8 5 2 9, we know that the first selection of 1st elements 5 will exchange with 2, therefore, the relative order of the two 5 in the original sequence is damaged. Therefore, selecting sorting is not a stable sorting algorithm.
Method 1:
Template
Void SelectSort (T a [], int n)
{
For (int I = n-1; I> 0; -- I)
{
Int max = I;
For (int j = 0; j <I; ++ j)
If (a [j]> a [max])
Max = j;
If (max! = I)
Swap (a [I], a [max]);
}
}
Method 2:
Template
Void SelectSort (T a [], int n)
{
For (int I = n-1; I> 0; -- I)
{
Int max = 0;
For (int j = 1; j <= I; ++ j)
If (a [j]> a [max])
Max = j;
If (max! = I)
Swap (a [I], a [max]);
}
}
Method 3:
Template
Void SelectSort (T a [], int n)
{
Bool sorted = false;
For (int I = n-1 ;! Sorted & I> 0; -- I)
{
Sorted = true;
Int max = 0;
For (int j = 1; j <= I; ++ j)
{
If (a [j]> a [max])
Max = j;
Else
Sorted = false;
}
If (max! = I)
Swap (a [I], a [max]);
}
}
Method 2 and method 3 are more like Bubble sorting, but there are still differences. At least the number of exchanges decreases.
For method 1 and method 2, the number of comparisons is O (n ^ 2). The number of comparisons has nothing to do with the initial state of the keyword. The best and worst cases are O (n ^ 2 ), but for method 3, it is best to execute the outer loop only once, and execute n-1 times in it. Therefore, the time complexity is O (n), and the worst case is O (n ^ 2 ).
Zookeeper