基础算法回顾

来源:互联网 发布:js判断是否等于0 编辑:程序博客网 时间:2024/06/18 01:59

#1 经典排序算法 – 插入排序Insertion sort  
插入排序就是每一步都将一个待排数据按其大小插入到已经排序的数据中的适当位置,直到全部插入完毕。 
插入排序方法分直接插入排序和折半插入排序两种,这里只介绍直接插入排序,折半插入排序留到“查找”内容中进行。 
  图1演示了对4个元素进行直接插入排序的过程,共需要(a),(b),(c)三次插入。

Image(6)

以下代码仅供参考,欢迎指正

static void insertion_sort(int[] unsorted)        {            for (int i = 1; i < unsorted.Length; i++)            {                if (unsorted[i - 1] > unsorted[i])  //                {                    int temp = unsorted[i];                    int j = i;                    while (j > 0 && unsorted[j - 1] > temp)                    {                        unsorted[j] = unsorted[j - 1];                        j--;                    }                    unsorted[j] = temp;                }            }        }


#include <stdio.h>  void insert_sort(int arr[], int n) {     int i, j;     int temp = 0;      for(i = 1; i < n; i++)     {          temp = arr[i]; //取出一个元素          //取出的元素和其前面的元素相比较          for(j = i; j > 0 && temp < arr[j - 1]; j--)          {              //如果前面的元素较大,则后移一位              if(temp < arr[j - 1])              {                  arr[j] = arr[j - 1];              }          }          //取出的元素填充到前面的元素空位          arr[j] = temp;      }    }    int main()  {      int i;      //实例数组      int arr[5] = {20, 30, 24, 40, 35};      insert_sort(arr, 5);      for(i = 0; i < 5; i++)      {          printf("%4d",arr[i]);      }  }


证明算法正确性:

Loop Invariants(mathematical induction)

for i = 2 to n
 - key = A[i]
 - j = i - 1
 - while j > 0 AND A[j] > key
  A[j+1] = A[j]
  j = j -1
 - A[j+1] = key


Outer loop: At the start of i-th iteration, A[1 .. i-1] is sorted
Inner loop: At the start of j-th iteration, elements of A[j+1 .. i-1]
are greater than “key” and the elements of A[1 .. j-1] are less than
or equal to “key”.



十种经典排序算法总结和实现

http://blog.csdn.net/jnu_simba/article/details/9705111

原创粉丝点击