您的位置:首页 > 理论基础 > 数据结构算法

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

2017-08-16 22:49 190 查看

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

Time Limit: 1000MS
Memory Limit: 65536KB

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

注意:数据相等时不做交换

#include<iostream>
#include<cstdio>
using namespace std;
void pai(int a[],int first,int last,int &n)
{
if(first>=last)
return ;
int low=first;
int high=last;
int temp=a[first]; //快排的改进版
while(low<high)
{
while(low<high&&temp<=a[high])
high--;
if(low<high&&temp>a[high]) //需要加上low<high的条件
{
a[low]=a[high];
n++;
}
while(low<high&&a[low]<=temp)
low++;
if(low<high&&a[low]>temp)
{
a[high]=a[low];
n++;
}
}
a[low]=temp;
pai(a,first,low-1,n); //子序列接着进行快排 递归
pai(a,low+1,last,n);
}
int maopao(int a[],int len)
{
int n=0;
for(int i=0;i<len-1;i++)
for(int j=i+1;j<len;j++)
{
if(a[i]>a[j])
{
int temp=a[i];
a[i]=a[j];
a[j]=temp;
n++;
}
}
return n;
}
int main()
{
int n;
while(cin>>n&&n!=EOF)
{
int *p=new int
;
int *q=new int
;
for(int i=0;i<n;i++)
{
cin>>p[i];
q[i]=p[i];
}
int x=0;
pai(p,0,n-1,x);
cout<<maopao(q,n)<<" "<<x<<endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: