冒泡排序

#include <iostream>

void print_arrs(const int *, int N);

void sort_arrs(int *pInt, int N);

int main() {
    int arr[] = {1, 3, 5, 7, 6, 2, 4, 9, 8, 0};
    std::cout << "排序前:" << std::endl;
    print_arrs(arr, 10);
    sort_arrs(arr, 10);
    std::cout << "排序后:" << std::endl;
    print_arrs(arr, 10);
    return 0;
}

/**
 * 冒泡排序
 * @param pInt 
 * @param N 
 */
void sort_arrs(int *const pInt, int N) {
    int temp;
    for (int i = N; i > 0; --i) {
        bool flag = false;//是否有交换标识
        for (int j = 0; j < i; ++j) {
            if (pInt[j] > pInt[j + 1]) {
                flag = true;
                temp = pInt[j + 1];
                pInt[j + 1] = pInt[j];
                pInt[j] = temp;
            }
        }

        if (!flag) break; //全程无交换
    }


}

void print_arrs(const int *pInt, int N) {
    for (int i = 0; i < N; ++i) {
        std::cout << pInt[i] << "\t";
    }
    std::cout << std::endl;
}

posted @ 2021-03-30 13:06  FlowLiver  阅读(38)  评论(0)    收藏  举报