sorter Template

by Jesterok on December 28th, 2009
No notes
Syntax: C++
Show lines - Hide lines - Show in textbox - Download
  1. #include <cstdlib>
  2. #include <iostream>
  3. using namespace std;
  4.  
  5. template<class T>
  6. class bSort
  7. {
  8. public:
  9. bSort(int _max){ //конструктор: распределяем память для массива и устанавливаем начальное значение счетчика
  10. array = new T[_max-1];
  11. max = _max;
  12. count = 0;
  13.  
  14. }
  15. ~bSort(){ delete[] array; } //деструктор: освобождаем память
  16.  
  17. void add_item(T item)
  18. {
  19. if(count<max){
  20. array[count] = item;
  21. count++;
  22. }
  23. }
  24.  
  25. void clear() //очищаем массив
  26. {
  27. array = new T[max-1];
  28. count = 0;
  29. }
  30.  
  31. void sort_this()const //сортировка пузырьком
  32. {
  33. T buf;
  34. for (int i = 0; i<count; i++){
  35. for (int j = 0; j<count-(i-1); j++){
  36. if (array[j]>array[j+1]){
  37. buf = array[j];
  38. array[j] = array[j+1];
  39. array[j+1] = buf;
  40. }
  41. }
  42. }
  43. }
  44.  
  45. T &operator[](int index)const //перегружаем оператор [] (будем использовать для вывода на экран)
  46. {
  47. return array[index];
  48. }
  49.  
  50. private:
  51. T* array; //указатель на тип данных
  52. int count, max; //размеренность массива
  53. };
  54.  
  55.  
  56.  
  57. int main()
  58. {
  59. int n, cur_numb;
  60. //вводим размеренность массива, и заполняем его
  61. cin>>n;
  62. bSort<int> srt(n);
  63. for(int i = 0; i<n; i++){
  64. cin>>cur_numb;
  65. srt.add_item(cur_numb);
  66. }
  67. srt.sort_this();
  68. //вывод массива
  69. for(int i = 0; i<n; i++){
  70. cout<<srt[i]<<' ';
  71. }
  72.  
  73. cin.get();
  74. cin>>n;
  75. return 0;
  76. }
  77.  

Leave a Reply

Note: XHTML is allowed. Your email address will never be published.

Subscribe to this comment feed via RSS