数据结构实验之排序二:交换排序
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
注意:数据相等时不做交换
Author
xam
#include <iostream>
#include <stdio.h>
using namespace std;
int cnt1,cnt2;
void q_sort(int a[], int left, int right)
{
if(left >= right)
return;
int i, j;
int temp;
i = left;
j = right;
temp = a[left];
while(i!= j)
{
while(i < j&& a[j] >= temp)
{
j--;
}
if(j > i)
{
a[i] = a[j];
cnt1++;
}
while(i < j && a[i] <= temp)
{
i++;
}
if(j > i)
{
a[j] = a[i];
cnt1++;
}
}
a[i] = temp;
q_sort(a,left,i-1);
q_sort(a,i+1,right);
}
void b_sort(int a[], int n)
{
int i, j, temp;
for (j = 0; j < n - 1; j++)
for (i = 0; i < n - 1 - j; i++)
{
if(a[i] > a[i + 1])
{
temp = a[i];
a[i] = a[i + 1];
a[i + 1] = temp;
cnt2++;
}
}
}
int main()
{
int n;
int qs[100000],bs[100000];
while(scanf("%d", &n) != EOF)
{
cnt1 = cnt2 = 0;
int i;
for(i = 0; i < n; i++)
{
int t;
scanf("%d", &t);
qs[i]= bs[i] = t;
}
q_sort(qs,0,n-1);
b_sort(bs,n);
printf("%d %d\n", cnt2, cnt1);
}
return 0;
}