排序

来源:互联网 发布:计算机的发展史软件 编辑:程序博客网 时间:2024/05/27 21:03

一、起泡排序

#include <iostream>#include <cstdio>#include <cstring>#include <cstdlib>#include <algorithm>#include <queue>#include <vector>#include <stack>#include <map>#include <cmath>#include <cctype>using namespace std;typedef long long ll;typedef unsigned long long ull;typedef unsigned int uint;const ull mod = 1e9 + 7;const int INF = 0x7fffffff;const int maxn = 1e6 + 10;int n;int num[maxn];void bubbleSort(int low, int high);bool bubble(int low, int high);int main(){#ifdef __AiR_H    freopen("in.txt", "r", stdin);#endif // __AiR_H    scanf("%d", &n);    for (int i = 0; i < n; ++i) {        scanf("%d", &num[i]);    }    bubbleSort(0, n);    for (int i = 0; i < n; ++i) {        printf("%d ", num[i]);    }    return 0;}void bubbleSort(int low, int high){    while (!bubble(low, high--));}bool bubble(int low, int high){    bool sorted = true;    while (++low < high) {        if (num[low-1] > num[low]) {            sorted = false;            swap(num[low], num[low-1]);        }    }    return sorted;}

#include <iostream>#include <cstdio>#include <cstring>#include <cstdlib>#include <algorithm>#include <queue>#include <vector>#include <stack>#include <map>#include <cmath>#include <cctype>using namespace std;typedef long long ll;typedef unsigned long long ull;typedef unsigned int uint;const ull mod = 1e9 + 7;const int INF = 0x7fffffff;const int maxn = 1e6 + 10;int n;int num[maxn];void bubbleSort(int low, int high);int bubble(int low, int high);int main(){#ifdef __AiR_H    freopen("in.txt", "r", stdin);#endif // __AiR_H    scanf("%d", &n);    for (int i = 0; i < n; ++i) {        scanf("%d", &num[i]);    }    bubbleSort(0, n);    for (int i = 0; i < n; ++i) {        printf("%d ", num[i]);    }    return 0;}void bubbleSort(int low, int high){    while (low < high) {        high = bubble(low, high);    }}int bubble(int low, int high){    int last = low;    while (++low < high) {        if (num[low-1] > num[low]) {            last = low;            swap(num[low], num[low-1]);        }    }    return last;}









0 0
原创粉丝点击