排序

sort(begin,end,cmp)

泡沫排序

/*
 * zerojudge
 * a225. 明明愛排列
 * C++
 * AC (26ms, 332KB)
*/
#include<bits/stdc++.h>
using namespace std;

int main(){
	int n;
	while(cin >> n){
		int a[n];
		for(int i=0;i<n;i++){
			cin >> a[i];
		}
		//
		for(int i=0;i<n;i++){
			for(int j=0;j<n-1;j++){
				if(a[j]%10 > a[j+1]%10){
					int temp = a[j];
					a[j]=a[j+1];
					a[j+1]=temp;
				}else if(a[j]%10 == a[j+1]%10){
					if(a[j]<a[j+1]){
						int temp = a[j];
						a[j]=a[j+1];
						a[j+1]=temp;
					}
				}
			}
		}
		//
		for(int i=0;i<n;i++){
			cout << a[i] << " ";
		}
		cout << endl;
	}
}

快速排序

/*
 * TIOJ
 * 1287 . C.基礎排序
*/
#include<bits/stdc++.h>
using namespace std;

bool cmp(int a,int b){
    return a<b; // <最前面是小的 ; >最前面是大的
}

int main(){
    ios_base::sync_with_stdio(0),cin.tie(0);
    int n;
    while(cin >> n){
        int arr[n];
        for(int i=0;i<n;++i){
           cin >> arr[i];
        }
        sort(arr,arr+n,cmp);
        for(int i=0;i<n;++i){
            cout << arr[i];
            if(i!=n-1){
                cout << " ";
            }
        }
        cout << endl;
    }
}

穩定排序 (面對同樣的值 不會影響原來的排序)

/*
 * CSES
 * Results of submission #391452
*/
#include<bits/stdc++.h>
using namespace std;

struct P{
    int value;
    int one;
};

bool cmp(P a,P b){
    return a.one<b.one;
}

int main(){
    int n;
    cin >> n;
    P arr[n];
    for(int i=0;i<n;++i){
        cin >> arr[i].value;
        arr[i].one = __builtin_popcount(arr[i].value);
    }
    stable_sort(arr,arr+n,cmp);
    for(int i=0;i<n;++i){
        cout << arr[i].value;
        if(i!=n-1){
            cout << " ";
        }
    }
    cout << endl;
}

特定排序

/*
 * zerojudge
 * c531. 基礎排序 #1-1 ( 偶數排序 )
*/
#include <bits/stdc++.h>
using namespace std;

bool isMove(int n){
    return (n%2==0);
}

int main() {
    ios_base::sync_with_stdio(0), cin.tie(0);
    string line;
    while(getline(cin, line)){
        for (int i = 0; i < line.size(); ++i) {
            if (line[i] == ',') {
                line[i] = ' ';
            }
        }
        stringstream ss(line);
        vector<int>v;
        vector<int>moveIndex;
        vector<int>moveNum;
        int x;
        int cnt = 0;
        while (ss >> x) {
            if(isMove(x)){
                moveNum.push_back(x);
                moveIndex.push_back(cnt);
            }
            v.push_back(x);
            cnt+=1;
        }
        sort(moveNum.begin(), moveNum.end());
        for (int i = 0; i < moveIndex.size(); ++i) {
            v[moveIndex[i]] = moveNum[i];
        }
        for (int i = 0; i < v.size(); ++i) {
            cout << v[i];
            if(i!=v.size()-1){
                cout << ",";
            }
        }
        cout << endl;
    }
    return 0;
}

Last updated

Was this helpful?