冒泡排序

稳定排序算法,时间复杂度:O(n2). 空间复杂度O(1);

#include<iostream>
using namespace std;
void print(int testlist[],int n) {
    for (int i = 0; i < n; i++) {
        cout << testlist[i] << endl;
    }
}
void bubble_sort(int testlist[],int n) {
    for (int i = 0; i < n - 1; i++) {
        for (int j = 0; j < n - i - 1; j++) {
            if (testlist[j] > testlist[j + 1]) {
                int temp = testlist[j+1];
                testlist[j+1] = testlist[j];
                testlist[j] = temp;
            }
        }
    }
}
int main() {
    int testlist[5] = { 2,3,4,1,0 };
    bubble_sort(testlist,5);
    print(testlist,5);
    system("pause");
    return 0;
}

选择排序

稳定排序算法 时间复杂度O(n2),空间复杂度O(1)

#include<iostream>
using namespace std;
void print(int testlist[],int n) {
    for (int i = 0; i < n; i++) {
        cout << testlist[i] << endl;
    }
}
void select_sort(int testlist[], int n) {
    for (int i = 0; i < n - 1; i++) {
        int min_index = i;
        for (int j = i + 1; j < n; j++) {
            if (testlist[j] < testlist[min_index]) {
                int temp = testlist[min_index];
                testlist[min_index] = testlist[j];
                testlist[j] = temp;
            }
        }
    }
}
int main() {
    int testlist[5] = { 2,3,4,1,0 };
    select_sort(testlist,5);
    print(testlist,5);
    system("pause");
    return 0;
}

快速排序

不稳定算法 时间复杂度O(logn), 空间复杂度O(1)

#include<iostream>
using namespace std;
void print(int testlist[],int n) {
    for (int i = 0; i < n; i++) {
        cout << testlist[i] << endl;
    }
}
int temp;
void quick_sort(int testlist[], int start,int end) {
    if (start < end) {
        int i = start;
        int j = end;
        int base = testlist[i];
        while (i < j){
            while (i < j && testlist[j] >= base) {
                j -= 1;
            }
            temp = testlist[i];
            testlist[i] = testlist[j];
            testlist[j] = temp;
            while (i < j && testlist[i] <= base) {
                i += 1;
            }
            temp = testlist[i];
            testlist[i] = testlist[j];
            testlist[j] = temp;
        }
        base = testlist[i];
        quick_sort(testlist, start, i - 1);
        quick_sort(testlist, i + 1, end);
    }
}
int main() {
    int testlist[5] = { 2,3,4,0,1 };
    quick_sort(testlist,0,4);
    print(testlist,5);
    system("pause");
    return 0;
}