Problem Description
冒泡排序和快速排序都是基于"交换"进行的排序方法,你的任务是对题目给定的N个(长整型范围内的)整数从小到大排序,输出用冒泡和快排对这N个数排序分别需要进行的数据交换次数。
Input
连续多组输入数据,每组数据第一行给出正整数N(N ≤ 10^5),随后给出N个整数,数字间以空格分隔。
Output
输出数据占一行,代表冒泡排序和快速排序进行排序分别需要的交换次数,数字间以1个空格分隔,行末不得有多余空格。
Sample Input
8
49 38 65 97 76 13 27 49
Sample Output
15 9
Hint
注意:数据相等时不做交换
Source
xam
注:
快排是不稳定排序,所以进行交换需要判断数据是否相等
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int a[10005];
int b[10005];
int b_count = 0;
int q_count = 0;
void b_sort(int* a, int n){
for (int i = 0; i < n-1; i++){
for (int j = 0; j < n-i-1; j++){
if (a[j] > a[j+1]){
b_count++;
int t = a[j];
a[j] = a[j+1];
a[j+1] = t;
}
}
}
}
void q_sort(int* arr, int left, int right){
if (left < right){
int i = left;
int j = right;
int key = arr[left];
while (i < j){
while (i < j && arr[j] >= key){
j--;
}
if (a[i] != a[j]){ // 元素相同则不交换位置
arr[i] = arr[j];
q_count++;
}
while (i < j && arr[i] <= key){
i++;
}
if (a[i] != a[j]){
arr[j] = arr[i];
q_count++;
}
}
arr[i] = key;
q_sort(arr, left, i-1);
q_sort(arr, i+1, right);
}
}
int main(){
int n;
while (~scanf("%d", &n)){
b_count = 0;
q_count = 0;
for (int i = 0; i < n; i++){
scanf("%d", &a[i]);
b[i] = a[i];
}
b_sort(a, n);
q_sort(b, 0, n-1);
printf("%d %d\n", b_count, q_count);
}
return 0;
}