插入排序(Insertion Sort)
2015-08-12 10:01
302 查看
这是排序算法中最常见的排序方法,也是初学者使用最多的。有时候我们在生活中也会不自觉地用到插入排序,例如:
给手里的牌排序
这是最常见的例子之一,我们通常从纸牌的一边开始看,找到一张位置不正确的,把它拿出来,再从开始的位置开始找,直到找到合适者张牌插入的位置。
假设手里有这几张牌2,4,6,3,10,K,J。排序的步骤如下:
[align=left]假设我们从左边开始看,2位置正确,4位置正确,6位置正确,3错误,他比前面的6要小。[/align]
[align=left]需要给3重新找到正确位置。[/align]
[align=left]取出3这张牌,冲头开始看,3比2大,再往后,3比4小,因此3插入2和4之间的位置。现在纸牌的顺序变成了2,3,4,6,10,K,J。[/align]
[align=left]接着上次我们离开的点开始看(就是3的位置,现在变成了6),6位置正确,10位置正确,K位置正确,J位置不正确,因为他比前面的K小。[/align]
[align=left]把J拿出来,重头开始看,J比2,3,4,6,10都大,比K小,因此插在10和K之间。[/align]
排序就完成了,手里的纸牌也变成了正确的顺序,这种方法就叫做插入排序。
相应的算法设计:
Start scanning the elements from 2nd position. The 1st is assumed to be at correct place.
[align=left]if ( arr[i] < arr[i-1])[/align]
Swap arr[i] and arr[i-1]
Keep swapping until the number is less than the previous number
The array gets sorted as we reach the end.
下面是具体执行代码:
时间复杂度:
Average Case:- O(n2)
Best Case:- O(n)
Worst Case:- O(n2)
给手里的牌排序
这是最常见的例子之一,我们通常从纸牌的一边开始看,找到一张位置不正确的,把它拿出来,再从开始的位置开始找,直到找到合适者张牌插入的位置。
假设手里有这几张牌2,4,6,3,10,K,J。排序的步骤如下:
[align=left]假设我们从左边开始看,2位置正确,4位置正确,6位置正确,3错误,他比前面的6要小。[/align]
[align=left]需要给3重新找到正确位置。[/align]
[align=left]取出3这张牌,冲头开始看,3比2大,再往后,3比4小,因此3插入2和4之间的位置。现在纸牌的顺序变成了2,3,4,6,10,K,J。[/align]
[align=left]接着上次我们离开的点开始看(就是3的位置,现在变成了6),6位置正确,10位置正确,K位置正确,J位置不正确,因为他比前面的K小。[/align]
[align=left]把J拿出来,重头开始看,J比2,3,4,6,10都大,比K小,因此插在10和K之间。[/align]
排序就完成了,手里的纸牌也变成了正确的顺序,这种方法就叫做插入排序。
相应的算法设计:
Start scanning the elements from 2nd position. The 1st is assumed to be at correct place.
[align=left]if ( arr[i] < arr[i-1])[/align]
Swap arr[i] and arr[i-1]
Keep swapping until the number is less than the previous number
The array gets sorted as we reach the end.
下面是具体执行代码:
#include<stdio.h> // function to swap two integers void swap(int *x, int *y) { int temp = *x; *x = *y; *y = temp; } // a function to perform Insertion Sort on the array arr with size specified void insertionSort(int arr[],int size) { int i,j; // iterating from 2nd element to the last for(i=1;i<size;i++) { if(arr[i] < arr[i-1]) { j = i; while(arr[j-1] > arr[j]) { // swapping all the numbers // until the next number is smaller than previous number swap(&arr[j],&arr[j-1]); j--; } } } } // driver function to test the above function int main(void) { int i; int arr[10] = {3, 4, 7, 1, 10, 8, 2, 22, 99, 50}; insertionSort(arr,10); printf("SORTED array:- "); for(i=0;i<10;i++) printf("%d ",arr[i]); return 0; }
时间复杂度:
Average Case:- O(n2)
Best Case:- O(n)
Worst Case:- O(n2)
相关文章推荐
- 人民币主动贬值:你的理财方式主动调整了吗?
- Python简介
- SM32W108无线射频模块多个节点之间通信实例
- less语法:(一)变量与extend
- 金典 SQL笔记(7)
- Application的作用
- 一篇文章为你解读大数据的现在和未来
- 本地化下按首字母分组排序的神器——UILocalizedIndexedCollation
- EasyUI学习笔记6:MIS开发利器_ datagrid插件(上)
- 手动生成MyEclipse注册码及序列号(源代码)
- Qt之日常积累
- HTML介绍JS
- Devexpress EXCEL导出
- POJ 2186 Popular Cows
- 人民币贬值如何影响你的生活
- Qt 5.x 中文翻译缺失的一种解决办法
- Spring学习笔记五(JDKProxy和cglibProxy的区别)
- 聊天机器人&语音
- EasyUI学习笔记5:来点甜点_ menu和theme插件
- DOM学习笔记