数据结构实验之排序二:交换排序
Time Limit: 1000ms Memory limit: 65536K 有疑问?点这里^_^
题目描述
冒泡排序和快速排序都是基于"交换"进行的排序方法,你的任务是对题目给定的N个(长整型范围内的)整数从小到大排序,输出用冒泡和快排对这N个数排序分别需要进行的数据交换次数。
输入
连续多组输入数据,每组数据第一行给出正整数N(N ≤ 10^5),随后给出N个整数,数字间以空格分隔。
输出
输出数据占一行,代表冒泡排序和快速排序进行排序分别需要的交换次数,数字间以1个空格分隔,行末不得有多余空格。
示例输入
8
49 38 65 97 76 13 27 49
示例输出
15 9
提示
注意:数据相等时不做交换
Time Limit: 1000ms Memory limit: 65536K 有疑问?点这里^_^
题目描述
冒泡排序和快速排序都是基于"交换"进行的排序方法,你的任务是对题目给定的N个(长整型范围内的)整数从小到大排序,输出用冒泡和快排对这N个数排序分别需要进行的数据交换次数。
输入
连续多组输入数据,每组数据第一行给出正整数N(N ≤ 10^5),随后给出N个整数,数字间以空格分隔。
输出
输出数据占一行,代表冒泡排序和快速排序进行排序分别需要的交换次数,数字间以1个空格分隔,行末不得有多余空格。
示例输入
8
49 38 65 97 76 13 27 49
示例输出
15 9
提示
注意:数据相等时不做交换
# include <stdio.h>
void quick_sort(long a[],int left,int right);
void bubble_sort(long a[],int len);
int qcnt;
int main()
{
int i,N;
long a[10000];
long b[10000];
while( (scanf("%d",&N)) !=EOF)
{
for(i=0;i<N;i++)
{
scanf("%ld",&a[i]);
b[i] = a[i];
}
bubble_sort(b,N);
qcnt = 0;
quick_sort(a,0,N-1);
printf("%d\n",qcnt);
}
return 0;
}
void bubble_sort(long a[],int len)
{
int i,j,t;
int cnt=0;
for(i=0;i<len-1;i++) // len-1 趟冒泡
{
for(j=0;j<len-1-i;j++)//每趟冒泡定一个最大的放在该趟的最后一位
{
if(a[j]>a[j+1])
{
t = a[j];
a[j] = a[j+1];
a[j+1] = t;
cnt++;
}
}
}
printf("%d ",cnt);
}
void quick_sort(long a[],int left,int right)
{
int low = left;
int high = right;
int temp = a[low];
if(low < high)
{
while(low < high)
{
while(low < high && a[high] >= temp)
{
high--;
}
if(a[low]!=a[high]) //注意:数据相等时不做交换. 一开始明白明明while循环的条件为a[high] >= temp怎么会出现相等.
{ // 其实忽视了 low < high 的条件,也就是循坏退出可能是 low = high 所致,此时的a[low] 可能等于a[high]
qcnt++; //但是不需要交换.所以要加上if!!!!
}
a[low] = a[high];
while(low < high && a[low] <= temp)
{
low++;
}
if(a[low]!=a[high])
{
qcnt++;
}
a[high] = a[low];
}
a[low] = temp;
quick_sort(a,left,low-1);
quick_sort(a,low+1,right);
}
}