您的位置:首页 > 编程语言 > Go语言

Introduction: Analysis of Algorithms, Insertion Sort, Merge Sort

2013-12-12 16:53 375 查看
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!

  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: