Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <string>
- using namespace std;
- const int N = 20;
- int getMax(int arr[], int n){
- int max = arr[0];
- for (int i = 1; i < n; i++)
- if (arr[i] > max)
- max = arr[i];
- return max;
- }
- void countSort(int arr[], int n, string tab[], int exp){
- int B[n], i, C[10] = {0};
- string BB[n];
- for (i = 0; i < n; i++) C[(arr[i] / exp) % 10]++;
- for (i = 1; i < 10; i++) C[i] += C[i-1];
- for (i = n - 1; i >= 0; i--) {
- C[(arr[i] / exp) % 10]--;
- B[C[(arr[i] / exp) % 10]] = arr[i];
- BB[C[(arr[i] / exp) % 10]] = tab[i];
- }
- for (i = 0; i < n; i++) {
- arr[i] = B[i];
- tab[i] = BB[i];
- }
- }
- void sortByLength(int arr[], string tab[], int n){
- int exp, max;
- max = getMax(arr, n); // Wyszukujemy najwieksza liczbe w calej tabeli, aby wykonywac algorytm dla ilosci cyft tej liczby
- for (exp = 1; max/exp > 0; exp *= 10)
- countSort(arr, n, tab, exp);
- }
- void sortByPost(string a[], int pos, int from, int to){
- string *b = new string[to - from + 1];
- int *c = new int[26];
- for (int i = 0; i <26; i++) c[i] = 0;
- for (int i = from; i <= to; i++) c[a[i][pos]-'a' ]++;
- for (int i = 1; i <26; i++) c[i] += c[i - 1];
- for (int i = to; i >= from; i--) {
- b[c[a[i][pos] -'a' ]- 1] = a[i];
- c[a[i][pos] -'a']--;
- }
- for (int i = from; i <= to; i++) a[i] = b[i - from];
- delete [] b;
- delete [] c;
- }
- void sort(string tab[], int N){
- int l[N];
- for(int i = 0; i < N; i++) l[i] = tab[i].length() - 1;
- sortByLength(l, tab, N);
- int from = N - 1;
- int pos = l[N - 1];
- while(from >= 0){
- while(from > 0 && l[from] == l[from - 1]) from--;
- do{
- sortByPost(tab, pos, from, N - 1);
- pos--;
- if(pos < 0) return;
- if(from > 0 && l[from - 1] == pos + 1)
- break;
- } while(true);
- from--;
- }
- }
- int main() {
- string tab[N] = {"garek", "monitor", "drzwi", "rower", "auto", "tablet", "garek", "czesiek", "ogienow", "frydrych",
- "kartka", "dlugopis", "kubek", "widelec", "biurko", "alaa", "ala", "gareczek", "dekster", "glut"};
- sort(tab, N);
- for(int i = 0; i < N; i++) cout << tab[i] << endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement