Advertisement
Guest User

Untitled

a guest
Mar 19th, 2019
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.32 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3. using namespace std;
  4.  
  5. const int N = 20;
  6.  
  7. int getMax(int arr[], int n){
  8. int max = arr[0];
  9. for (int i = 1; i < n; i++)
  10. if (arr[i] > max)
  11. max = arr[i];
  12. return max;
  13. }
  14.  
  15. void countSort(int arr[], int n, string tab[], int exp){
  16. int B[n], i, C[10] = {0};
  17. string BB[n];
  18. for (i = 0; i < n; i++) C[(arr[i] / exp) % 10]++;
  19. for (i = 1; i < 10; i++) C[i] += C[i-1];
  20. for (i = n - 1; i >= 0; i--) {
  21. C[(arr[i] / exp) % 10]--;
  22. B[C[(arr[i] / exp) % 10]] = arr[i];
  23. BB[C[(arr[i] / exp) % 10]] = tab[i];
  24. }
  25. for (i = 0; i < n; i++) {
  26. arr[i] = B[i];
  27. tab[i] = BB[i];
  28. }
  29. }
  30.  
  31. void sortByLength(int arr[], string tab[], int n){
  32. int exp, max;
  33. max = getMax(arr, n); // Wyszukujemy najwieksza liczbe w calej tabeli, aby wykonywac algorytm dla ilosci cyft tej liczby
  34.  
  35. for (exp = 1; max/exp > 0; exp *= 10)
  36. countSort(arr, n, tab, exp);
  37. }
  38. void sortByPost(string a[], int pos, int from, int to){
  39. string *b = new string[to - from + 1];
  40. int *c = new int[26];
  41.  
  42. for (int i = 0; i <26; i++) c[i] = 0;
  43. for (int i = from; i <= to; i++) c[a[i][pos]-'a' ]++;
  44. for (int i = 1; i <26; i++) c[i] += c[i - 1];
  45. for (int i = to; i >= from; i--) {
  46. b[c[a[i][pos] -'a' ]- 1] = a[i];
  47. c[a[i][pos] -'a']--;
  48. }
  49. for (int i = from; i <= to; i++) a[i] = b[i - from];
  50. delete [] b;
  51. delete [] c;
  52. }
  53.  
  54. void sort(string tab[], int N){
  55. int l[N];
  56. for(int i = 0; i < N; i++) l[i] = tab[i].length() - 1;
  57. sortByLength(l, tab, N);
  58.  
  59. int from = N - 1;
  60. int pos = l[N - 1];
  61.  
  62. while(from >= 0){
  63. while(from > 0 && l[from] == l[from - 1]) from--;
  64.  
  65. do{
  66. sortByPost(tab, pos, from, N - 1);
  67. pos--;
  68. if(pos < 0) return;
  69. if(from > 0 && l[from - 1] == pos + 1)
  70. break;
  71. } while(true);
  72. from--;
  73. }
  74. }
  75.  
  76. int main() {
  77. string tab[N] = {"garek", "monitor", "drzwi", "rower", "auto", "tablet", "garek", "czesiek", "ogienow", "frydrych",
  78. "kartka", "dlugopis", "kubek", "widelec", "biurko", "alaa", "ala", "gareczek", "dekster", "glut"};
  79. sort(tab, N);
  80.  
  81. for(int i = 0; i < N; i++) cout << tab[i] << endl;
  82. return 0;
  83. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement