c语言算法说明怎么写,C语言的几个算法排序说明.doc

算法排序

/xiajun0座机电话号码/article/details/座机电话号码

下面简要总结了常用的一些排序算法。如有错误,还请大家指正、见谅~~谢谢~~

【1】插入排序:

是一个对少量元素进行排序的有效算法。实现比较简单。时间复杂度:O n^2 ,空间复杂度:O 1 。是稳定的排序方法。

代码:

view plaincopy to clipboardprint?

//insertion?sort #include using?namespace?std;??

//insertion?sort void?InsertionSort int?*a,int?n int?temp; for int?i? ?1;i? ?n;++i temp? ?* a?+?i ; int?j? ?i?-?1; while j? ?0?&&?* a?+?j ? ?temp * a?+?j?+?1 ? ?* a?+?j ; --j; * a?+?j?+?1 ? ?temp; int?main int?n,temp; cout "please?input?the?number?of?the?values?that?need?to?sort:" endl; cin n; int?*a? ? int* malloc n?*?sizeof int ; cout "please?input?each?value:" endl; for int?i? ?0;i? ?n;++i cin temp; * a?+?i ? ?temp; /* //insertion?sort for int?i? ?1;i? ?n;++i temp? ?* a?+?i ; int?j? ?i?-?1; while j? ?0?&&?* a?+?j ? ?temp * a?+?j?+?1 ? ?* a?+?j ; --j; * a?+?j?+?1 ? ?temp; */ InsertionSort a,n ; cout "the?values?after?sort:" endl; for int?i? ?0;i? ?n;++i cout * a?+?i "?";??

view plaincopy to clipboardprint?

free a ;??

view plaincopy to clipboardprint 数据测试:

上述代码可以改进的一个地方是:在查找插入位置的时候可以采用二分查找,但是这样依然不可以把时间复杂度降低为O nlogn ,因为移动元素的复杂度没有降低。所以时间复杂度仍然是O n^2 。

做此改进需要添加函数InsertLoc用于二分查找需要插入的位置,以及修改函数InsertionSort的实现。具体如下:

view plaincopy to clipboardprint?

//改进:用二分查找来找到插入的位置 //在数组a[low]a[high]查找val插入的位置 int?InsertLoc int?*a,int?low,int?high,int?val if low? ?high if val? ?* a?+?low return? low?+?1 ; else return?low; int?mid? ? low?+?high ?/?2; if val? ?* a?+?mid ?&&?val? ?* a?+?mid?+?1 return?InsertLoc a,mid?+?1,high,val ; else?if val? ?* a?+?mid ?&&?val? ?* a?+?mid?+?1 return?InsertLoc a,low,mid,val ; else return?mid; void?InsertionSort int?*a,int?n int?temp,insert_location; for int?i? ?1;i? ?n;++i temp? ?* a?+?i ; int?j? ?i?-?1; insert_location? ?InsertLoc a,0,j,temp ; cout "insert_location:" insert_location endl; while j? ?insert_location * a?+?j?+?1 ? ?* a?+?j ; --j; * a?+?insert_location ? ?temp; for int?m? ?0;m? ?i;++m cout * a?+?m "?"; cout endl; 【2】选择排序

第一次找出A[0,...,n-1]的最小的元素,与A[0]交换,接着,找出A[1,...,n-1]的次小得元素,与A[1]互换

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值