ALGORITHM
You will have a record into the sorted order of the table (while the original bar cis elements on the rearward shifted position), to thereby obtain a sorted list of the new record number 1 is increased.
Algorithmic process
Performance Analysis
(1) Time Complexity Analysis
Whatever the case, the outer loop is always executed one by one, the number of cycles for the external n
-
Consider the worst case, i.e. the entire sequence are in reverse order, the inner loop is executed one required, the internal number of cycles (n-1) / 2, so the total number of cycles n (n-1) / 2, the algorithm complexity is O (n ^ 2)
-
Consider the best case, that the whole sequence is the order, the inner loop needs not performed, into a single double-loop cycle, so the total number of cycles is n, the complexity of the algorithm is O (n)
-
An average case, complexity of the algorithm is O (n ^ 2)
Complexity (2) Spatial Analysis
Algorithm requires an auxiliary storage space does not change with changes in the size of a column to be sorted, is a constant, so the space complexity is O (1)
(3) Stability
If the two key value records A and B are equal, A first insert, the insert B, A sorted this time, the order of B remains the same, so this known sorting algorithm is stable.
achieve
void insertSort(int R[],int n) //待排关键字存储在R[]中,个数为n
{
int i,j;
int temp;
for(i=0;i<n;i++)
{
temp=R[i];
j=i-1;
while(j>=0&&temp<R[j])
{
R[j+1]=R[j]; // 将原来位置上的元素向后顺移
--j;
}
R[j+1]=temp; // 找到插入位置,将temp中暂存的待排关键字插入
}
}