You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
std:sort is most likely to use QuickSort, or at least a variation over QuickSort called IntroSort, which "degenerates" to HeapSortwhen the recursion goes too deep. From the standard:
The order of equal elements is not guaranteed to be preserved.
Complexity: O(n log n) comparisons.
std::stable_sort is most likely to use MergeSort, because of the stability requirement. However note that MergeSort requires extra space in order to be efficient. From the standard:
The order of equal elements is guaranteed to be preserved.
Complexity: It does at most (n log n)2 comparisons; if enough extra memory is available, it is n log n.
This function attempts to allocate a temporary buffer equal in size to the sequence to be sorted. If the allocation fails, the less efficient algorithm((n log n)2) is chosen.
// C++ implementation of Counting Sort
#include<bits/stdc++.h>usingnamespacestd;intmain(void)
{
ios::sync_with_stdio(false);
cin.tie(NULL);
// k : 1 ~ 200int arr[] = {174,84,75,22,123,24,2,78};
int freq[1+200]; // 0, 1 ~ kmemset(freq,0,sizeof freq);
// n timesfor (int i : arr) {
++freq[i];
}
// k times + n times// when for-statement completes k iterations, // while-loop executes a total of n operations// => 2n + k, O(n + k)for (int i = 1; i<=200; ++i) {
//while (freq[i]--) {
cout << i << '';
}
}
cout << '\n';
return0;
}
// https://www.acmicpc.net/problem/10989
#include<bits/stdc++.h>usingnamespacestd;intmain(void)
{
ios::sync_with_stdio(false);
cin.tie(NULL);
staticint freq[10'001];
int low = 10'000;
int high = 1;
int n;
cin>>n;
// n timesfor (int i = 0; i<n; ++i) {
int temp;
cin>>temp;
++freq[temp];
low=min(low,temp);
high=max(high,temp);
}
// k times + n timesfor (int i = low; i<=high; ++i) {
while (freq[i]--) {
cout << i << '\n';
}
}
return0;
}
Radix Sort (기수 정렬)
기타 정렬 (Non-comparison Sort)
대상 간 비교를 직접 하지 않음
비교해야 할 대상 수가 n이고, 기수(radix)의 수가 l, 대상의 범위가 k일 때, 시간복잡도는 O(l×(n+k))이고 공간복잡도는 O(n+k)
// C++ implementation of Radix Sort
#include<bits/stdc++.h>usingnamespacestd;intmain(void)
{
ios::sync_with_stdio(false);
cin.tie(NULL);
int arr[] = {174,84,75,22,723,24,2,78};
int n = sizeof arr/sizeof(int);
int max_n = 0;
for (int i : arr) {
max_n=max(max_n,i);
}
// Radix Sort// the digit represented by d// l timesfor (int d = 1; max_n/d>0; d*=10) {
vector<int> v[10];
// n timesfor (int i = 0; i<n; ++i) {
int idx = (arr[i]/d)%10;
v[idx].push_back(arr[i]);
}
// k timesint i = 0;
for (int j = 0; j<10; ++j) {
for (auto elem : v[j]) {
arr[i++]=elem;
}
}
}
for (int i : arr) {
cout << i << '';
}
cout << '\n';
return0;
}