insert-sorting

Introduction to Algorithms, 2nd Edition, P19

Discriptions:

Input: A sequence of n numbers a1, a2, . . .,an.
• Output: A permutation (reordering) a1', a2', ..., an'of the input sequence such that a1' <= a2' <=...<=an'.

Pseudcodes

INSERTION-SORT(A)
1 for j ← 2 to length[A]
2 do key ← A[j]
3 ▹ Insert A[j] into the sorted sequence A[1 j - 1].
4 i ← j - 1
5 while i > 0 and A[i] > key
6 do A[i + 1] ← A[i]
7 i ← i - 1
8 A[i + 1] ← key

My codes in C++:

#include  < iostream >

using  std::cout;
using  std::cin;
using  std::endl;

#define  MAX 100

int  main()
{
    
int A[MAX]; //定义数组

    
int i=0;
    
int j,key,num; 
    
    
/*输入数组*/
    
while(cin >> A[i])
        i
++;      
    num
=i;  //记录数组元素个数

    
for(j=1; j< num; j++)  //从第二个元素开始插入
    {
        key 
= A[j];
        
for(i = j-1; i>=0 && A[i] > key; --i) 
            A[i
+1]=A[i];
            A[
++i]=key;
                
    }


    
for(i=0; i< num; i++)
        cout 
<< A[i] <<endl;
    
    
return 0;

}

 Analysis:

INSERTION-SORT(A) cost times
1 for j ← 2 to length[A] c1 n
2 do key ← A[j] c2 n - 1
3 ▹ Insert A[j] into the sorted
sequence A[1 j - 1]. 0 n - 1
4 i ← j - 1 c4 n - 1
5 while i > 0 and A[i] > key c5
6 do A[i + 1] ← A[i] c6
7 i ← i - 1 c7
8 A[i + 1] ← key c8 n - 1
The running time of the algorithm is the sum of running times for each statement executed; a
statement that takes ci steps to execute and is executed n times will contribute cin to the total
running time.[5] To compute T(n), the running time of INSERTION-SORT, we sum the
products of the cost and times columns, obtaining

Even for inputs of a given size, an algorithm's running time may depend on which input of
that size is given. For example, in INSERTION-SORT, the best case occurs if the array is
already sorted. For each j = 2, 3, . . . , n, we then find that A[i] ≤ key in line 5 when i has its
initial value of j - 1. Thus tj = 1 for j = 2, 3, . . . , n, and the best-case running time is
T(n) = c1n + c2(n - 1) + c4(n - 1) + c5(n - 1) + c8(n - 1)
= (c1 + c2 + c4 + c5 + c8)n - (c2+ c4 + c5 + c8).

If the array is in reverse sorted order-that is, in decreasing order-the worst case results. We
must compare each element A[j] with each element in the entire sorted subarray A[1 j - 1],
and so tj = j for j = 2, 3, . . . , n. Noting that n*(n+1)/2-1.This worst-case running time can be expressed as an2 + bn + c for constants a, b, and c that again depend on the statement costs ci ; it is thus a quadratic function of n.

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值