[C++]数据结构-排序:插入排序之直接插入排序
得赶紧休息了,木有时间写原理了。直接上代码。
/* <插入排序-直接插入排序> */
#include<iostream>
using namespace std;
void print(int *nodes, int length){
for(int i=0;i<length;i++){ //notice: No equal sign in middle condition, otherwise the last node will be error
printf("%d\t", nodes[i]);
}
printf("\n");
}
void InsertSort(int *nodes,int length){
for(int i=2;i<length;i++){
if(nodes[i] < nodes[i-1]){//default:ascending order
nodes[0] = nodes[i]; //set nodes[0] as a sentry or flag
int j;
for(j=i-1;nodes[0] < nodes[j];j--){
nodes[j+1] = nodes[j];
}
nodes[j+1] = nodes[0];
}
}
}
/* 直接插入排序(Insertion Sorting)
[1] init thought:
foreach:nodes[2...n] as nodes(i)
set 哨兵nodes(0) = nodes(i);
foreach:nodes[i-1...n] as nodes(j)
if nodes(j).key <= nodes(0).key
nodes(j+1) = nodes(j);
else
break;
nodes[j+1] = nodes[0];
*/
int main(){
int nodes[11] = {0,1,3,64,5,57,33,32,53,7509,6578};
print(nodes,11);
InsertSort(nodes,11);
print(nodes,11);
return 0;
}
output

本文作者:
千千寰宇
本文链接: https://www.cnblogs.com/johnnyzen
关于博文:评论和私信会在第一时间回复,或直接私信我。
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
日常交流:大数据与软件开发-QQ交流群: 774386015 【入群二维码】参见左下角。您的支持、鼓励是博主技术写作的重要动力!
本文链接: https://www.cnblogs.com/johnnyzen
关于博文:评论和私信会在第一时间回复,或直接私信我。
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
日常交流:大数据与软件开发-QQ交流群: 774386015 【入群二维码】参见左下角。您的支持、鼓励是博主技术写作的重要动力!

浙公网安备 33010602011771号