冒泡排序
#include<iostream>
#include<algorithm>
using namespace std;
int main() {
int n;
int a[1000];
while (cin >> n) {
for (int i = 0; i < n; i++) {
cin >> a[i];
}
for (int i = 0; i < n-1; i++) {
for (int j = n-1; j >i; j--) {
if (a[j-1] > a[j]) {
swap(a[j-1], a[j]);
}
}
}
for (int i = 0; i < n; i++) {
cout << a[i] << " ";
}
cout << endl;
}
}
快速排序
#include<iostream>
#include<algorithm>
using namespace std;
int Parition(int a[], int low, int high) {
int pivot = a[low];
while (low < high) {
while (low < high&&a[high] >= pivot)
--high;
a[low] = a[high];
while (low < high&&a[low] <= pivot)
++low;
a[high] = a[low];
}
a[low] = pivot;
return low;
}
void QuickSort(int a[], int low, int high) {
if (low < high) {
int pivotpos = Parition(a, low, high);
QuickSort(a, low, pivotpos - 1);
QuickSort(a, pivotpos + 1, high);
}
}
int main() {
int n;
int a[1000];
while (cin >> n) {
for (int i = 0; i < n; i++) {
cin >> a[i];
}
QuickSort(a, 0, n - 1);
for (int i = 0; i < n; i++) {
cout << a[i] << " ";
}
cout << endl;
}
return 0;
}
Top K问题
优先级队列内部实现是堆,可以用来快速求Top K问题。
#include<iostream>
#include<queue>
#include<vector>
using namespace std;
int main() {
priority_queue<int> a; //默认大顶堆
priority_queue<int, vector<int>, greater<int>> c; //小顶堆
int nums[1000];
int n, k;
while (cin >> n >> k) {
for (int i = 0; i < n; i++) {
cin >> nums[i];
a.push(nums[i]);
c.push(nums[i]);
}
while (!a.empty()) {
cout << a.top() << " ";
a.pop();
}
cout << endl;
for (int i = 0; i < k;i++) {
cout << c.top() << " ";
c.pop();
}
cout << endl;
}
}