• 数据结构实验之排序二:交换排序


     

    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

    注意:数据相等时不做交换

    #include <iostream>
    using namespace std;
    
    int a[100050],b[100050];
    int mpnum=0,kpnum=0; //次数记录
    
    int sort(int min,int max)
    {
    	int i=min,j=max,book;
    	if(i>=j)
    		return 0;
    	book=a[i];
    	while(i<j)
    	{
    		while(i<j&&a[j]>=book)
    			j--;
    		a[i]=a[j];
    		if(i<j)
    		   kpnum++;
    		while(i<j&&a[i]<=book)
    			i++;
    		a[j]=a[i];
    		if(i<j)
    		   kpnum++;
    	}
    	a[i]=book;
    	sort(min,i-1);
    	sort(i+1,max);
    }
    
    void maopao(int max)
    {
    	int i,j,temp;
    	for(i=1;i<=max;i++)
    	{
    		for(j=1;j<=max-i;j++)
    		{
    			if(b[j]>b[j+1])
    			{
    				mpnum++;
    				temp=b[j];
    				b[j]=b[j+1];
    				b[j+1]=temp;
    			}		
    		}
    	}
    }
    
    
    int main()
    {
    	int i,j,n;
    	while(cin>>n)
    	{
    		mpnum=kpnum=0;
    		for(i=1;i<=n;i++)
    		{
    			cin>>a[i];
    			b[i]=a[i];
    		}
    		sort(1,n);
    		maopao(n);
    		cout<<mpnum<<" "<<kpnum<<endl;
    	}
    	return 0;
    }

  • 相关阅读:
    JSP_core
    J2EE_Servlet——helloworld
    JS_对象原型链
    JDBC_Hive & coding
    Python错误——TypeError: 'NoneType' object is not iterable
    Python错误——TypeError: is_leap_year() takes 0 positional arguments but 1 was given
    python错误:sh: cls: command not found
    Git——版本控制系统
    samba服务器搭建+权限设置
    windows10 samba 安全策略无法访问
  • 原文地址:https://www.cnblogs.com/TheProcess/p/6179061.html
Copyright © 2020-2023  润新知