c_cpp 插入排序

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp 插入排序相关的知识,希望对你有一定的参考价值。

#include <bits/stdc++.h>
using namespace std;

//  #Sorting #Theory

void InsertionSort(vector<int> &a){    // passing vector by reference
    int n=a.size();
    for(int i=1;i<n;i++){   // starting from x=1
        int key=a[i];   //storing it in a temp key variable
        int j=i-1;      // starting from prev element of key
        while(j>=0){    // move upto staring postion of array backwards
            if(a[j]>key){   // if the element is greater than key
                a[j+1]=a[j];    // move it to the right as right place is empty(stored in key)
            }else{
                break;  // else stop
            }
            j--;
        }
        // we need to reinsert key at the next postion of where a[j]<key
        // it also works in case j goes to -1 without breaks in loop
        // so insert at j+1 index
        a[j+1]=key;
    }
}

int main(){
    int t;
    cin>>t;
    while(t--){
        int n;
        cin>>n;
        vector<int> a(n);
        for(int i=0;i<n;i++){
            cin>>a[i];
        }
        cout<<"Original: ";
        for(int i=0;i<n;i++){
            cout<<a[i]<<" ";
        }
        cout<<endl;
        InsertionSort(a);
        cout<<"Sorted: ";
        for(int i=0;i<n;i++){
            cout<<a[i]<<" ";
        }
        cout<<endl;
        
    }
    
    return 0;
}

以上是关于c_cpp 插入排序的主要内容,如果未能解决你的问题,请参考以下文章

c_cpp 插入排序

c_cpp 插入排序

c_cpp 插入排序

c_cpp 插入排序

c_cpp 插入排序的.cpp

c_cpp 递归C插入排序