アルゴリズム学習ノート (C++) - 並べ替えと検索

アルゴリズム学習ノート (C++) - 並べ替えと検索

分類する

ソートは C++ のアルゴリズムに組み込まれており、sort と入力することで呼び出すことができます。デフォルトは int 型の昇順ソートであり、必要に応じてソート方法 Compare を定義できます。


以下に使用例を示します。

トピック:
学生の名前とスコアを入力し、学生の名前とスコアが降順または昇順で出力されることを期待します。学生のスコアが同じ場合、最初に入力した学生が最初に出力することが期待されます。

入力:
1行目の生徒数、
2行目のソート方法(0が降順、1が昇順)
以降のn行は名前+スペース+得点

出力 (n 行):
各行の内容は次のとおりです: (指定された方法でソート) 名前 + スペース + スコア

注:
sortはint型の昇順がデフォルトです
が、この問題では名前、成績、入力順をまとめて保存する必要があるため、Studentという構造体をカプセル化し、自分で定義したCompare関数を使用する必要があります。

# include <cstdio>
# include <iostream>
# include <algorithm>
# include <string>

using namespace std;

struct Student{
    
    
	string name;
	int score;
	int order;
};

// increasing, type 1
bool AscendingCompare(Student a, Student b){
    
    
	if (a.score == b.score){
    
    
		return a.order < b.order;
	}
	else{
    
    
		return a.score < b.score;
	}
}

// decreasing, type 0
bool DescendingCompare(Student a, Student b){
    
    
	if (a.score == b.score){
    
    
		return a.order < b.order;
	}
	else{
    
    
		return a.score > b.score;
	}
}

int main(){
    
    
	// total number of student and compare method
	int number, type;
	cin >> number >> type;
	Student arr[number];
	// load name, score and order
	for (int i=0; i<number; ++i){
    
    
		cin >> arr[i].name;
		cin >> arr[i].score;
		arr[i].order = i;
	}
	// compare with appointed method
	if(type){
    
    
		sort(arr, arr+number, AscendingCompare);
	}
	else{
    
    
		sort(arr, arr+number, DescendingCompare);
	}
	// output
	for (int i=0;i<number; ++i){
    
    
		cout << arr[i].name << " " << arr[i].score << endl;
	}
	
	
	return 0;
}

例:
ここに画像の説明を挿入


見上げる

前のセクションでの並べ替えの意味の 1 つは、検索をより効率的に行えるようにすることです。順序付けされたシーケンスにより、要素を 1 つずつ比較することなく、検索効率が向上します。これは、同じシーケンス内で複数回検索する場合に非常に明白です。

ルックアップに関しては、ここで二分探索戦略を紹介します。

// binary search

# include <cstdio>
# include <iostream>
# include <algorithm>

using namespace std;
const int MAXN = 100;

int arr[MAXN];

bool binarySearch(int len, int target){
    
    
	int left = 0;
	int right = len-1;
	while(left <= right){
    
    
		int middle = (left + right) / 2;
		if (arr[middle] < target){
    
    			// drop the left half of arr
			left = middle + 1;
		}
		else if (arr[middle] > target){
    
    		// drop the right half of arr
			right = middle - 1;
		}
		else{
    
    								// find it
			return true;
		}
	}
	return false;
}


int main(){
    
    
	int len;
	int n;
	while(scanf("%d", &len) != EOF){
    
    
		// load data
		for (int i=0; i<len; ++i){
    
    
			cin >> arr[i];
		}
		// sort in Ascending
		sort(arr, arr+len);
		// binary search
		cin >> n;
		int target;
		while (n--){
    
    
			cin >> target;
			if (binarySearch(len, target)){
    
    
				printf("True\n");
			}
			else{
    
    
				printf("False\n");
			}
		}
	}
	return 0;
}

ここに画像の説明を挿入

おすすめ

転載: blog.csdn.net/m0_53327618/article/details/124514812