Advertisement
Guest User

Untitled

a guest
Mar 22nd, 2018
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.41 KB | None | 0 0
  1. #include <iostream>
  2. #include <algorithm>
  3. #include <string>
  4. using namespace std;
  5.  
  6. /*
  7. return 0 if there is no character on declared position
  8. returns 1 for a, 2 for b etc.
  9. */
  10. int characterNumber(string number, int position) {
  11. if(position >= number.length()) return 0;
  12. return (int)(number[position] - 'a'+1);
  13. }
  14. void sortByPosition(string tab[], int n, int pos) {
  15. int k = 'z'-'a'+2; //+2 , bo oddzielnie traktuje a i NULL (0)
  16. int *counters = new int[k];
  17. string *result = new string[n];
  18. for(int i=0; i<k; i++) counters[i] = 0;
  19. for(int i = 0; i < n; i++) counters[characterNumber(tab[i], pos)]++;
  20. for(int i=1; i<k; i++) counters[i] += counters[i-1];
  21. for(int i=n-1; i>=0; i--) {
  22. result[--counters[characterNumber(tab[i], pos)]]=tab[i];
  23. }
  24.  
  25. for(int i = 0; i < n; i++) tab[i]=result[i];
  26.  
  27. delete [] counters;
  28. delete [] result;
  29. }
  30. void radixSort(string tab[], int n) {
  31. int maxLength = tab[0].length();
  32. for(int i = 1; i < n; i++)
  33. if(tab[i].length() > maxLength) maxLength = tab[i].length();
  34.  
  35. for(int i = maxLength-1; i >= 0; i--){
  36. sortByPosition(tab, n, i);
  37. }
  38. }
  39.  
  40. int main() {
  41. int n = 6;
  42. string strings[n];
  43. strings[0] = "abecadlo";
  44. strings[1] = "da";
  45. strings[2] = "aaa";
  46. strings[3] = "aa";
  47. strings[4] = "aaaa";
  48. strings[5] = "baca";
  49. radixSort(strings,n);
  50.  
  51. for(int i = 0; i < n; i++){
  52. cout << strings[i] << endl;
  53. }
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement