插入排序

来源:互联网 发布:树状笔记软件ubuntu 编辑:程序博客网 时间:2024/05/22 04:26
#include <iostream>#include <algorithm>using namespace std;void insert(int a[], int len){/*1.从第二个开始,把第二个抽出来当临时变量,这时假设这个位置是空的2.当左边的数据比这个临时变量大时,将左边的数值向右移动,  直到遇到左边,直到左边的数据小于这个临时变量为止3.将这个临时变量插入到这个空位置上  排序数组:5 7 4 2 6  第一次  temp = 75 0 4 2 6--》左边的比这个临时变量小,且已经到达了最左端5 7 4 2 6(结束)  第二次temp = 45 7 0 2 65 5 7 2 65 5 7 2 64 5 7 2 6 (结束)  第三次temp = 24 5 7 7 64 5 5 7 64 4 5 7 62 4 5 7 6 (结束) 第四次temp = 62 4 5 7 72 4 5 6 7 (结束) 因为左边的5比6小,所以就停止将左边的数据右移了,将临时变量插入到这里*/for (int i=1; i<len; i++){cout<<"第"<<i<<"次排序:"<<endl;int temp = a[i];//定义临时变量cout<<"temp = "<<temp<<endl;int j;//当 (j>0) 遇到最左端时,或者,(a[j-1] > temp) 左边的数据比这个临时变量小时,停止for (j=i; j>0&&a[j-1]>temp; j--){a[j] = a[j-1];//将左边的数值向右移到右边//循环输出,看看排序经过for (int y=0; y<len; y++){cout<<a[y]<<" ";}cout<<endl;}cout<<"要插入的位置 j = "<<j<<endl;cout<<"要插入的位置上的值 a[j] = "<<a[j]<<endl;a[j] = temp;//将这个临时变量插入到这个空位上//循环输出,看看排序经过cout<<"第"<<i<<"次排序后的结果:"<<endl;for (int k=0; k<len; k++){cout<<a[k]<<" ";}cout<<endl<<endl;}}void show(int a[], int len){for (int i=0; i<len; i++){cout<<a[i]<<" ";}cout<<endl;}int main(){int a[5] = {5,7,4,2,6};cout<<"插入排序:"<<endl;cout<<"排序前:"<<endl;show(a, 5);cout<<endl;insert(a, 5);cout<<endl;cout<<"排序后:"<<endl;show(a, 5);return 0;}