入门客AI创业平台(我带你入门,你带我飞行)
博文笔记

数据结构实验之排序二:交换排序

创建时间:2017-12-20 投稿人: 浏览次数:218

数据结构实验之排序二:交换排序
Time Limit: 1000MS Memory Limit: 65536KB
Submit Statistic
Problem Description
冒泡排序和快速排序都是基于”交换”进行的排序方法,你的任务是对题目给定的N个(长整型范围内的)整数从小到大排序,输出用冒泡和快排对这N个数排序分别需要进行的数据交换次数。

Input
连续多组输入数据,每组数据第一行给出正整数N(N ≤ 10^5),随后给出N个整数,数字间以空格分隔。

Output
输出数据占一行,代表冒泡排序和快速排序进行排序分别需要的交换次数,数字间以1个空格分隔,行末不得有多余空格。

Example Input
8
49 38 65 97 76 13 27 49
Example Output
15 9
Hint
注意:数据相等时不做交换

Author
xam

#include <iostream>
#include <string>
#include <cstring>
#include <stdio.h>
using namespace std;

const int MAX = 100005;
int cta;
int ctb;
//快速排序
void quickSort(int l, int r, int a[])
{
    if (l >= r)
        return;
    int i = l, j = r;
    int k = a[i];
    while (i < j)
    {
        while (i < j && a[j] >= k)
            j--;
        if (a[i] != a[j])
            ctb++;
        a[i] = a[j];
        while (i < j && a[i] <= k)
            i++;
        if (a[j] != a[i])
            ctb++;
        a[j] = a[i];
    }
    a[i] = k;
    quickSort(l, i - 1, a);
    quickSort(i + 1, r, a);
}

//冒泡排序
void bubbleSort(int a[], int n)
{
    int i, j, tp;
    for (i = 0; i < n - 1; i++)
    {
        for (j = 0; j < n - i - 1; j++)
        {
            if (a[j] > a[j + 1])
            {
                cta++;
                tp = a[j];
                a[j] = a[j + 1];
                a[j + 1] = tp;
            }
        }
    }
}
int main()
{
    int n;
    while (~scanf("%d", &n))
    {
        cta = 0;
        ctb = 0;
        int a[MAX];
        int i;
        int b[MAX];
        for (i = 0; i < n; i++)
        {
            scanf("%d", &a[i]);
            b[i] = a[i];
        }
        quickSort(0, n - 1, a);
        bubbleSort(b, n);
        printf("%d %d
", cta, ctb);
    }
    return 0;
}
阅读更多
声明:该文观点仅代表作者本人,入门客AI创业平台信息发布平台仅提供信息存储空间服务,如有疑问请联系rumenke@qq.com。
  • 上一篇:没有了
  • 下一篇:没有了
未上传头像