Guest User

Untitled

a guest
Oct 22nd, 2014
151
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.09 KB | None | 0 0
  1. //main.cpp
  2. #include <iostream>
  3. #include "sort.h"
  4.  
  5. int main()
  6. {
  7.     int *array;
  8.     int size, choice;
  9.  
  10.     std::cout << "Enter the size of array: ";
  11.     std::cin >> size;
  12.     array = new int[size];
  13.  
  14.     std::cout << "Enter the array:\n";
  15.     for(int i = 0; i < size; i++)
  16.         std::cin >> array[i];
  17.  
  18.     std::cout << "Choose the sort method:\n";
  19.     std::cout << "1. Quick sort\n"
  20.               << "2. Bubble sort\n";
  21.  
  22.     std::cin >> choice;
  23.  
  24.     switch(choice) {
  25.     case 1:
  26.         TSort sort(void *quickSort);
  27.         break;
  28.     }
  29.  
  30.     return 0;
  31. }
  32.  
  33. //sort.h
  34. #ifndef SORT_H
  35. #define SORT_H
  36. #include <iostream>
  37.  
  38. enum METHOD { QUICKSORT=1, BUBBLESORT };
  39.  
  40. class TSort
  41. {
  42.     void (*method)(int *array, int first, int last);
  43. public:
  44.     TSort(void (*method));
  45.     void operator()(int *array, int first, int last);
  46. };
  47.  
  48. void quickSort(int *array, int first, int last);
  49. void bubbleSort(int *array, int first, int last);
  50.  
  51.  
  52. #endif // SORT_H
  53.  
  54. //sort.cpp
  55.  
  56. #include "sort.h"
  57.  
  58. TSort::TSort(void (*method)) {
  59.     this->method = method;      // invalid conversion from 'void*' to 'void (*)(int*, int, int)
  60. }
  61.  
  62. void TSort::operator()(int *array, int first, int last) {
  63.     method(array, first, last);
  64. }
  65.  
  66. void quickSort(int *array, int first, int last) {
  67.     int i = first;
  68.     int j = last;
  69.     int m = array[(first + last) / 2];
  70.  
  71.     do {
  72.         while(array[i] < m) i++;
  73.         while(array[j] > m) j--;
  74.  
  75.         if(i <= j) {
  76.             if(array[i] > array[j]) {
  77.                 int temp = array[j];
  78.                 array[j] = array[i];
  79.                 array[i] = temp;
  80.             }
  81.             i++;
  82.             j++;
  83.         }
  84.     } while(i <= j);
  85.  
  86.     if(i < last)
  87.         quickSort(array, i, last);
  88.     if(j > first)
  89.         quickSort(array, first, j);
  90. }
  91.  
  92. void bubbleSort(int *array, int first, int last) {
  93.     for(int i = 0; i < last; i++)
  94.         for(int j = 0; j < last - i; j++)
  95.             if(array[j] > array[j+1]) {
  96.                 int temp = array[j];
  97.                 array[j] = array[j+1];
  98.                 array[j+1] = temp;
  99.             }
  100. }
Advertisement
Add Comment
Please, Sign In to add comment