简化桶排序 冒泡排序 快速排序

简化桶排序,时间复杂度为O(M+N)
#include<iostream>
using namespace std;
int main()
{
    int book[1001], t,n;
    cout << "需标记数的个数" << endl;
    cin >> n;
    for (int i = 0; i < 1001; i++)
    {
        book[i] = 0;
    }
    for (int i = 0; i < n; i++)
    {
        cin >> t;
        book[t]++;
    }
    for (int i = 1000; i>=0 ; i--)
    {
        for (int j = 0; j < book[i]; j++)
        {
            cout << i << " ";
        }
    }
    getchar(); getchar();
    return 0;
}

冒泡排序,时间复杂度为O(N2)
#include<iostream>
using namespace std;
int main()
{
    int a[100], t, n;
    cout << "要进行排序数的个数" << endl;
    cin >> n;
    cout << "输入数字" << endl;
    for (int i = 0; i < n; i++)
    {
        cin >> a[i];
    }
    for (int i = 0; i < n - 1; i++)
    {
        for (int j = 0; j < n - 1; j++)
        {
            if (a[j] < a[j + 1])
            {
                t = a[j];
                a[j] = a[j + 1];
                a[j + 1] = t;
            }
        }
    }

    for (int i = 0; i < n; i++)
    {
        cout << a[i] << "  ";
    }

    return 0;
}


#include<iostream>
using namespace std;

class Student
{
public:
    char name[21];
    int score;
};
int main()
{
    Student a[100],t;
    int  n;
    cout << "要进行排序数的个数" << endl;
    cin >> n;
    cout << "输入数字" << endl;
    for (int i = 0; i < n; i++)
    {
        cin >> a[i].name >> a[i].score;
    }
    for (int i = 0; i < n - 1; i++)
    {
        for (int j = 0; j < n - 1; j++)
        {
            if (a[j].score < a[j + 1].score)
            {
                t = a[j];
                a[j] = a[j + 1];
                a[j + 1] = t;
            }
        }
    }

    for (int i = 0; i < n; i++)
    {
        cout << a[i].name << "  ";
    }

    return 0;
}


快速排序
#include<iostream>
using namespace std;
int a[100], n;

void quicksort(int left, int right)
{
    int i, j, t, temp;
    if (left > right)
    {
        return;
    }
    temp = a[left];
    i = left;
    j = right;

    while (i != j)
    {
        while (a[j] >= temp && i < j)
        {
            j--;
        }
        while (a[i] <= temp && i < j)
        {
            i++;
        }
        if (i < j)
        {
            t = a[i];
            a[i] = a[j];
            a[j] = t;
        }
    }
    a[left] = a[i];
    a[i] = temp;
    quicksort(left, i - 1);
    quicksort(i+1,right);
}

扫描二维码关注公众号,回复: 5032282 查看本文章

int main()
{
    int i, j;
    cout << "数的个数" << endl;
    cin >> n;
    for (int i = 0; i < n; i++)
    {
        cin >> a[i];
    }
    quicksort(0, n-1);
    for (i = 0; i < n; i++)
    {
        cout << a[i] << " ";
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/a66666_/article/details/81369591
今日推荐