基础算法回顾
来源:互联网 发布:js判断是否等于0 编辑:程序博客网 时间:2024/06/18 01:59
#1 经典排序算法 – 插入排序Insertion sort
插入排序就是每一步都将一个待排数据按其大小插入到已经排序的数据中的适当位置,直到全部插入完毕。
插入排序方法分直接插入排序和折半插入排序两种,这里只介绍直接插入排序,折半插入排序留到“查找”内容中进行。
图1演示了对4个元素进行直接插入排序的过程,共需要(a),(b),(c)三次插入。
以下代码仅供参考,欢迎指正
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
阅读全文
0 0
- 基础算法回顾
- 算法基础_8大经典排序算法实现回顾
- 基础回顾
- 回顾基础
- C# 基础回顾
- C++基础的回顾
- Delphi 基础回顾
- Delphi 基础回顾2
- 基础部分回顾
- 基础部分回顾2
- C++基础回顾
- C++基础回顾(2)
- C++基础回顾(3)
- javaScript基础回顾
- 回顾技术,整理基础
- javascript基础回顾
- javascript基础小回顾
- javascript基础回顾3
- 再见阿里云,你好腾讯云
- java多线程
- 《C++ Primer》读书笔记第四章-2-类型转换
- 结合服务端和客户端使用protobuf
- webpack2.0搭建react框架环境
- 基础算法回顾
- 有关Java反射机制的作用及用法浅析
- 35. Search Insert Position
- Python入门(一) 安装python+pycharm
- 如何在JS页面中引入时间插件(简单时间)
- 异常
- ARM微处理器系列简介
- 观察者模式
- 集合