欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

插入排序和归并排序的总结

程序员文章站 2024-03-17 23:23:16
...

    插入排序的pesudocode 和c语言的实现,并且注释有详细的algorithms的时间的分析

/*
pesudocode

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

Running time 
	Depends on input sizes 
	 -- params in input size 
	upper bounds
	 -- guaranet the users 
	 
Kinds of analysis
	T(n)[this is a realtion to functions] = max time on any input of size n 
	T(n) = expected time over all input of size n 
	  {Need assumption of uniform distribution}

Best-case(bagus)
	cheat with with a slow algorithms

The time 
	Depends on computer 
	 -- relative speed(on same machine)
	 -- absolute speed(on diff machine)

THe big ideas of algorithms !! relay on asymptotic analysis(jian jin fenxi)
    1. ignore machine- dependent constants 
    2. Look at growth of T(n) as n -> wuqiong
    
    Asymptotic notations
     theta -- drop slow terms 
           --ignore the leading constants 
      
    worest case 
    	arithmetic 
     faster ?
        --  Not at all for large n 
    
Merge sort 
 		1) Merge sort A[1 .. n]
    	 if n = 1 done 
    	 Recursively sort A[1 .. n/2] and A[n/2 + 1 .. n]
    	 Merge them sort lists 
    	  key subroutine -- Merge
    	    20 13 7 2 
    	    12 11 9 1  TIme = theta(n) on n total elems liner time
    	    recursive  theta(nlgn) time faster than insertion sort
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>	
void insetsort(int *A, int length)
{
	int i = 0;
	int j = 0;
	int key;
	for (j = 1; j < length; j++)
	{
		key = A[j];
		i = j - 1;
		
		while(i > 0 && A[i] > key)
		{
			A[i + 1] = A[i];
			i = i - 1;
		}
		
		A[i + 1] = key;
	}
}

void main()
{
	int i = 0;
	int a[5] = {1, 5, 2, 4, 3};
	insetsort(a, 5);
	for(i = 0; i < 5; i++)
   		printf("%d\n", a[i]);
}