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
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
int n;
int sum1;
int a[100005],b[100005];
//冒泡排序
int maopao()
{
int i,j,temp;
int sum = 0;
for(i=1;i<=n-1;i++)
{
for(j=1;j<=n-i;j++)
{
if(a[j] > a[j+1])
{
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
sum++;
}
}
}
return sum;
}
//快速排序
void quicksort(int left,int right)
{
int i,j,temp;
if(left > right)
return ;
temp = b[left];
i = left;
j = right;
while(i < j)
{
while(b[j] >= temp && i<j)
j--;
b[i] = b[j];
if(i<j)
sum1 ++;
while(b[i] <= temp && i<j)
i++;
b[j] = b[i];
if(i<j)
sum1 ++;
}
b[i] = temp;
quicksort(left,i-1);
quicksort(i+1,right);
return ;
}
int main()
{
while(scanf("%d",&n)!=EOF)
{
sum1=0;
for(int i=1;i<=n;i++)
{
scanf("%d",&a[i]);
b[i] = a[i];
}
int p = maopao();
quicksort(1,n);
printf("%d %d\n",p,sum1);
}
return 0;
}