SDUT數據結構實驗之排序二:交換排序

數據結構實驗之排序二:交換排序

Time Limit: 1000 ms Memory Limit: 65536 KiB

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

注意:數據相等時不做交換

#include <stdio.h>
int cnt1, cnt2;
void qs(int a[], int l, int r)
{
	
	int i = l;
	int j = r;
	int key = a[l];
	if(i >=j)
	{
		return ;
	}
	while(i < j)
	{
		while(i < j && a[j] >= key)
			j--;
			if(a[i] != a[j])
			cnt1++;
			a[i] = a[j];
		
		while(i < j && a[i] <= key)
			i++;
			if(a[j] != a[i])
			cnt1++;
			a[j] = a[i];
	}
	a[i] = key;
	qs(a, l, i-1);
	qs(a, i+1, r);
}
void bbs(int a[] ,int n)
{
	int i, j, t;
	for(i = 0; i < n - 1; i++)
	{
		for(j = 0; j < n - 1 - i; j++)
		{
			if(a[j] > a[j+1])
			{
				cnt2++;
				t = a[j];
				a[j] = a[j + 1];
				a[j + 1] = t;
			}
		}
	}
	
}
int main()
{
	int n;
	int a[1005];
	while(~scanf("%d",&n))
	{
		cnt1 = 0;
		cnt2 = 0;
		int a[10005];
		int i;
		int  b[1005];
		for(i = 0; i < n; i++)
		{
			scanf("%d",&a[i]);
			b[i]  = a[i];
		}
		qs(a, 0, n-1);
		bbs(b,n);
		printf("%d %d\n",cnt2,cnt1);
	}
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章