First, the algorithm thought
Maximum selection table L (small) elements, switching elements and the final position. It comprises the following steps:
- For table L = (a1, az, a3 ,. ..., ai ..., an.), The order of traversal, the maximum element selected location, the last position of the switching element;
- For the remainder of the child table except the last element composed of repeating (1), until the remaining part of the sub-table is composed of a length equal to the.
Second, the algorithm process
Third, to achieve
void SelectSort(int R[],int n)
{
int i,j;
int temp;
int max_index;
for(i=0;i<n;i++)
{
max_index=-1;
for(j=0;j<n-i;j++)
{
if(R[j]>max_index)
max_index=j;
}
if(max_index>=0)
{
j--;
temp=R[max_index];
R[max_index]=R[j];
R[j]=temp;
}
}
}
Fourth, the algorithm performance analysis
(1) Time Complexity Analysis
Execution times of two cycles and the initial sequence does not matter, n times the outer loop, the inner loop is executed n-1 times, the comparison operation of the innermost loop as a key operation, which is performed n times (N- 1) / 2, so the average time complexity, worst case time complexity, are the best time complexity O (n ^ 2)
Complexity (2) Spatial Analysis
Space complexity is O (1)
(3) Stability
It can be seen from the statement if (R [j]> max_index), the algorithm will always encounter the maximum value added to the first sorted sequence (if they are the same value will be skipped), then the algorithm It is unstable. (If> into> =, the algorithm is stable, but this will increase the number of executions max_index = j)