4 solutions

  • 3
    @ 2024-1-20 11:38:43
    #include<bits/stdc++.h>
    using namespace std;
    int n;
    int a[10005];
    int s=0;//计次 
    bool enough(int a[]){//判断数组是否排序完成 
    	bool f=true;
    	for(int i=1;i<n;i++){
    		if(a[i]<a[i-1]) f=false;
    	}
    	return f;
    }
    int main(){
    	cin>>n;
    	for(int i=0;i<n;i++) cin>>a[i];
    	for(int i=0;i<n;i++){
    		for(int j=i+1;j<n;j++){
    			if(enough(a)){//如果满足就跳循环 
    				cout<<s<<endl;
    				return 0;//返回使运行结束 
    			}
    			if(a[i]>a[j]){
    				swap(a[i],a[j]);
    				s++;
    			}
    		}
    	}
    	//简单冒泡排 
    	cout<<s<<endl;//注意要再输出一遍 
    	return 0;
    }
    

    目前只想到用冒泡做 其他做法还请分享👀️

    • 0
      @ 2024-1-21 9:59:00
      #include<iostream>
      #include<cstdio>
      using namespace std;
      long n,i,j,t,s,a[10000];
      int main()
      {
          cin>>n;
          for (i=1;i<=n;i++)
            cin>>a[i];
          for (i=1;i<=n-1;i++)
            for (j=1;j<=n-i;j++)
            if(a[j]>a[j+1])
            {
              swap(a[j],a[j+1]);
              s++;
            };
             cout<<s;
             return 0;
      }
      
      • -1
        @ 2024-1-22 9:07:49
        #include<bits/stdc++.h>
        using namespace std;
        int n;
        int a[10005];
        int s=0;//计数器 
        int main(){
        	cin>>n;
        	for(int i=0;i<n;i++) cin>>a[i];
        	for(int i=0;i<n;i++){
        		for(int j=i+1;j<n;j++){
        			if(a[i]>a[j]){
        				swap(a[i],a[j]);
        				s++;
        			}
        		}
        	}//冒泡 
        	cout<<s<<endl;
        	return 0;
        }
        
        
        • -1
          @ 2024-1-21 9:56:36
          #include <bits/stdc++.h>
          using namespace std;
          int a[11111];
          int m = 0;
          void bubble_sort(int a[],int n)
          {
          	bool flat = true;
          	while(flat)
          	{
          		flat = false;
          		for(int i = 0;i < n - 1;i++)
          		{
          			if(a[i] > a[i + 1])
          			{
          				flat = true;
          				swap(a[i],a[i + 1]);
          				m++;
          			}
          		}
          	}
          }
          int main()
          {
          	int n;
          	cin >> n;
          	for(int i = 0;i < n;i++)
          	{
          		cin >> a[i];
          	}
          	bubble_sort(a,n);
          	cout << endl << m;
          	return 0;
          }
          
          
          • 1

          Information

          ID
          795
          Time
          1000ms
          Memory
          256MiB
          Difficulty
          4
          Tags
          # Submissions
          95
          Accepted
          47
          Uploaded By