Advertisement
Guest User

Untitled

a guest
Nov 30th, 2010
384
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.87 KB | None | 0 0
  1. #include <iostream>
  2. #include <cstdlib>
  3. #include <string>
  4. #include <vector>
  5. #include <sstream>
  6.  
  7. using namespace std;
  8.  
  9. template <typename T>
  10. static
  11. void carica (vector<T>& v)
  12. {
  13.     string temp;
  14.     stringstream* _in;
  15.     T tdbl;
  16.     bool ancora = true;
  17.  
  18.     cout << "Immetti i numeri da ordinare." << endl
  19.         << "Premi invio senza immettere nulla per terminare" << endl;
  20.  
  21.     do
  22.     {
  23.         cout << "Numero da inserire: ";
  24.         getline(cin, temp);
  25.         if (temp == "")
  26.             ancora = false;
  27.         else
  28.         {
  29.             _in = new stringstream(temp);
  30.             *_in >> tdbl;
  31.             if (!_in->fail())
  32.                 v.push_back(tdbl);
  33.             delete _in;
  34.         }
  35.     } while (ancora);
  36. }
  37.  
  38. template <typename T>
  39. static
  40. void stampa (const vector<T>& v)
  41. {
  42.     for (vector<T>::const_iterator i = v.begin(); i != v.end(); ++i)
  43.     {
  44.         if (i != v.begin()) cout << " ";
  45.         cout << *i;
  46.     }
  47.     cout << endl;
  48. }
  49.  
  50. template <typename T>
  51. static
  52. vector<T> ordina (const vector<T>& v)
  53. {
  54.     vector<T>::size_type sz = v.size();
  55.    
  56.     if (sz <= 1)
  57.         return v;
  58.     else
  59.     {
  60.         //Split phase
  61.         vector<T> sx(v.begin(), v.begin() + (sz / 2));
  62.         vector<T> dx(v.begin() + (sz / 2), v.end());
  63.  
  64.         //Recursive phase
  65.         sx = ordina(sx);
  66.         dx = ordina(dx);
  67.  
  68.         //Merge phase
  69.         vector<T> mix;
  70.         mix.reserve(sz);
  71.         vector<T>::const_iterator si = sx.begin(), send = sx.end();
  72.         vector<T>::const_iterator di = dx.begin(), dend = dx.end();
  73.         while (si != send && di != dend)
  74.             mix.push_back((*si < *di) ? *(si++) : *(di++));
  75.         while (si != send)
  76.             mix.push_back(*(si++));
  77.         while (di != dend)
  78.             mix.push_back(*(di++));
  79.         return mix;
  80.     }
  81. }
  82.  
  83. int main (int argc, char* argv[])
  84. {
  85.     cout << "Questo programma ordina un elenco di numeri" << endl;
  86.     vector<double> lista;
  87.  
  88.     carica(lista);
  89.     cout << endl << "Lista inserita:" << endl;
  90.     stampa(lista);
  91.     cout << endl;
  92.  
  93.     cout << "Lista ordinata:" << endl;
  94.     stampa(ordina(lista));
  95.     cout << endl;
  96.  
  97.     system("pause");
  98.     return 0;
  99. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement