Bubble sort, insertion sort and selection sort

#include<iostream>
using namespace std;
#define ElemType int
const int Maxn=105;
void InsertSort(ElemType A[],int n){
    int i,j;
    for(i=2;i<=n;i++){
        if(A[i]<A[i-1]){
            A[0]=A[i];
            for(j=i-1;A[j]>A[0];j--){
                A[j+1]=A[j];
            }
            A[j+1]=A[0];
        }
    }
}
// time: preferably O (n) and the worst average O (^ n-2)
 // Space: O (. 1)
 // stable 
void SelectSort (elemType A [], int n-) {
     for ( int I = 0 ; I <N- . 1 ; I ++ ) {
         int Mmin = I;
         for ( int J = I + . 1 ; J <n-; J ++ ) {
             IF (A [J] < A [Mmin])
                mmin=j;
        }
        if(mmin!=i)
            swap(A[i],A[mmin]);
    }
}
//时间:O(n^2)
//空间:O(1)
//不稳定 
void BubbleSort(ElemType A[],int n){
    for(int i=0;i<n-1;i++){
        bool f=false;
        for(int j=n-1;j>i;j--){
            if(A[j]<A[j-1]){
                f=true;
                swap(A[j],A[j-1]);
            }
        }
        if(!f)return;
    }
}
// time: preferably O (n) and the worst average O (^ n-2)
 // Space: O (. 1)
 // stable 
int main () {
     int n-;
    cin>>n;
    ElemType arr[Maxn];
    for(int i=1;i<=n;i++){
        cin>>arr[i];
    }
    //SelectSort(arr,n);
    //BubbleSort(arr,n);
    InsertSort(arr,n);
    for(int i=1;i<=n;i++){
        cout<<arr[i]<<" ";
    }
    cout<<endl;
    return 0;
}
//12
//8 2 9 3 23 7 2 6 4 1 16 7

 

Guess you like

Origin www.cnblogs.com/lyt888/p/12539742.html