Introduction: Analysis of Algorithms, Insertion Sort, Merge Sort

Sorting:

The problem of sorting:

Input: sequence <a1, a2,....an>

output: permutation<a1' , a2' ,....an'> such that a1'<=a2'<=a3'....<=an'


Inserting sort:

1)think at index j, the sequence of the  left index of j is sorted.

2)we insert j to the left sorted sequence, thus at current index j, it is sorted.

3)repeat this action form 2 to n

4)all elements has been add to sorted sequence.


pseudocode:

  /*INSERTION-SORT (A, n)     ⊳ A[1 . . n]
    for j ← 2 to n
        do key ← A[ j]
        i←j–1
          while i > 0 and A[i] > key
            do A[i+1] ← A[i]
              i←i–1
          A[i+1] = key

   * */

source code:

/*
 * BaseSortingCustom.h
 *
 *  Created on: 2013-12-11
 *      Author: deman
 */

#ifndef BASESORTINGCUSTOM_H_
#define BASESORTINGCUSTOM_H_

template <class T>
class BaseSortingCustom {
public:
  BaseSortingCustom(){}
  virtual ~BaseSortingCustom(){}

  /*INSERTION-SORT (A, n)     ⊳ A[1 . . n]
    for j ← 2 to n
        do key ← A[ j]
        i←j–1
          while i > 0 and A[i] > key
            do A[i+1] ← A[i]
              i←i–1
          A[i+1] = key
   * */
  void InsertingSort(T A[], int n)
  {
    T key;
    int i =0,j=0;

    for(j = 2;j<=n;j++)
    {
      key = A[j-1];
      i = j-1;

      while(i>0 && A[i-1]>key)
      {
        A[i] = A[i-1];
        i = i-1;
      }
      A[i] = key;
    }
  }

};





#endif /* BASESORTINGCUSTOM_H_ */

Running Time:

T(n) = maximum time of algorithm on any input of size n.

What is inserting sort worst-case time:

T ( n) =
n
Θ( j ) = Θ(n 2 )
∑

Merge Sort:

for A[1...n]

if n=1, Sort is OK

if n>1 , it depends two divided part, A[1,.....[n/2]+1], and A[[n/2]+1,.....n];


T(n) = 2T(n/2)+Θ(n);

consider this case, cn->c n/2 + c n/2 ->c n/4 + cn/4 + cn/4 +cn/4 ...... ->C+C+....C

which means: work cn can be devided with cn/2 and plus cn/2 ....

thus , cn can be devided to n *C work.  and the devided work is lgn

so: T(n) = Cn*lgn = Θ(nlgn).

the example showing how it works.

first we make two part is sorted sequence. like below.

Each time we conpaire the first element of child sequence, and move the small one to the desert array.

thus , each time what we campaired is the first place of child sequences. this can be repeat work until, the two sequence has been  ordered!

It is better than inserting sort!








  


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值