关闭

insert-sorting

468人阅读 评论(0) 收藏 举报

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.

 

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:251366次
    • 积分:3446
    • 等级:
    • 排名:第9654名
    • 原创:82篇
    • 转载:49篇
    • 译文:2篇
    • 评论:47条
    最新评论