读书笔记:算法导论第2章 第2节分析算法

1. Exercise 2.2-1

Question:Express the function n^3 /1000-100n^2-100n+3 in terms of  Θ-notation.

Answer: Θ(n^3)


2. Exercise 2.2-2

Question: Consider sorting n numbers stored in array A by first finding the smallest element of A and exchanging it with the element in A[1]. Then find the second smallest
element of A, and exchange it with A[2]. Continue in this manner for the first n-1 elements of A. Write pseudocode for this algorithm, which is known as selection sort. What loop invariant does this algorithm maintain? Why does it need to run for only the first n-1 elements, rather than for all n elements? Give the best-case and worst-case running times of selection sort in Θ-notation.

Answer:
Source code:

void selectionSort(int *a, int len)
{
    int i, j, min, index, temp;
    for(i = 0; i < len - 1; i++){
        min = a[i];
        index = 0;
        for(j = i + 1; j < len; j++){
            if(a[j] < min){
                min = a[j];
                index = j;
            }
        }
        if(index != 0){
            temp = a[i];
            a[i] = a[index];
            a[index] = temp;
        }
    }
}

Loop invariant: 在第4~18行的for循环的每次迭代开始时,子数组a[0...i-1]由比子数组a[i...n-1]中任意元素小的元素组成,并已排好序。

It needs to run for only the first n-1 elements, rather than for all n elements,  just because loop invariant determines it.

The best-case running times of selection sort: Θ(n^2).
The worst-case running times of selection sort : Θ(n^2).


3. Exercise 2.2-3 

Question:Consider linear search again (see Exercise 2.1-3). How many elements of the input sequence need to be checked on the average, assuming that the element being
searched for is equally likely to be any element in the array? How about in the worst case? What are the average-case and worst-case running times of linear search in Θ-notation? Justify your answers.

Answer:

Source code

void linearSearch(int *a, int len, int v)
{
    int i, flag;
    flag = 0;

    for(i = 0; i < len; i++){
        if(a[i] == v){
            flag = 1;
            printf("a[%d] == %d\n", i, v);
        }
    }

    if(flag == 0)
        printf("%d does not exist in this array.\n", v);
}

Half the elements of the input sequence need to be checked on the average.

The average-case and worst-case running times of linear search is Θ(n).








  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值