九大经典排序算法

#include <iostream>  //冒泡排序 O(n^2)
using namespace std;
int main(int argc, const char * argv[]) {
    int a[10]={9,8,7,6,5,4,3,2,1};
    for (int i=1; i<=8; i++) {
        for (int j=0; j<=8-i; j++) {
            if (a[j] > a[j+1]) {
                swap(a[j], a[j+1]);
            }
        }
    }
    for (int i=0; i<=8; i++) { printf("%d ",a[i]); } printf("\n");
    return 0;
}
#include <iostream> // 选择排序 O(n^2)
using namespace std;
int main(int argc, const char * argv[]) {
    int a[11]={9,8,7,6,5,4,3,2,1,10};
     for (int i=0; i<=9; i++) {
         for (int j=i+1; j<=9; j++) {
             if(a[i]>a[j]){
                 swap(a[j], a[i]);
             }
         }
     }
    for (int i=0; i<=9; i++) { printf("%d ",a[i]); } printf("\n");
    return 0;
}
#include <iostream> // 插入排序 O(n^2)
using namespace std;
int main(int argc, const char * argv[]) {
    int a[11]={9,5,4,8,7,6,3,2,1,10};
     for (int i=1; i<=9; i++) {
         int key;
         key = a[i];
         for (int j=i; j>=0; j--) {
             if(key < a[j]){
                 a[j+1] = a[j];
                 a[j] = key;
             }
         }
     }
    for (int i=0; i<=9; i++) { printf("%d ",a[i]); } printf("\n");
    return 0;
}


猜你喜欢

转载自blog.csdn.net/guokaigdg/article/details/79356221
今日推荐