当前位置: 移动技术网 > IT编程>开发语言>C/C++ > c++实现插入排序(代码教程)

c++实现插入排序(代码教程)

2018年01月07日  | 移动技术网IT编程  | 我要评论

瑕不掩瑜造句,青岛小哥骂雅阁女,三国之无敌吕布

插入排序的重点在于从后往前面的有序列推进,需要注意到达终点时的处理与其他不同。

#include 
using namespace std;
int arr[1001];

void insert_sort(int n){
    int tmp;
    for(int i = 1; i < n; i++){
        tmp = arr[i];
        for(int j = i-1; j >= 0; j--) 
            if(tmp < arr[j]) {
                arr[j+1] = arr[j]; 
                if(j == 0) { arr[0] = tmp; break; } //arrive the end
            }
            else {
                arr[j+1] = tmp;
                break;
            }    
    }  
}

int main(){
    int n;
    cin >> n;
    for(int i = 0; i < n; i++) cin >> arr[i];
    insert_sort(n);
    for(int i = 0; i < n; i++) cout << arr[i] << " ";
    cout << endl;
}

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网