Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //main.cpp
- #include <iostream>
- #include "sort.h"
- int main()
- {
- int *array;
- int size, type;
- std::cout << "Enter the size of array: ";
- std::cin >> size;
- array = new int[size];
- std::cout << "Enter the array:\n";
- for(int i = 0; i < size; i++)
- std::cin >> array[i];
- std::cout << "Choose the sort method:\n";
- std::cout << "1. Quick sort\n"
- << "2. Bubble sort\n"
- << "3. Insert sort\n";
- std::cin >> type;
- TSort sort(type);
- sort(array, 0, size);
- std::cout << "Sorting the elements...\n";
- for(int i = 0; i < size; i++)
- std::cout << array[i] << " ";
- return 0;
- }
- //sort.h
- #ifndef SORT_H
- #define SORT_H
- #include <iostream>
- enum METHOD { QUICKSORT=1, BUBBLESORT, INSERTSORT };
- class TSort
- {
- void (*method)(int *array, int first, int last);
- public:
- TSort(int type);
- void operator()(int *array, int first, int last);
- };
- #endif // SORT_H
- //sort.cpp
- #include "sort.h"
- void quickSort(int *array, int first, int last) {
- last = last - 1;
- int i = first;
- int j = last;
- int m = array[(first + last) / 2];
- do {
- while(array[i] < m) i++;
- while(array[j] > m) j--;
- if(i <= j) {
- if(array[i] > array[j]) {
- int temp = array[j];
- array[j] = array[i];
- array[i] = temp;
- }
- i++;
- j++;
- }
- } while(i <= j);
- if(i < last)
- quickSort(array, i, last);
- if(j > first)
- quickSort(array, first, j);
- }
- void bubbleSort(int *array, int first, int last) {
- last = last - 1;
- for(int i = 0; i < last; i++)
- for(int j = 0; j < last - i; j++)
- if(array[j] > array[j+1]) {
- int temp = array[j];
- array[j] = array[j+1];
- array[j+1] = temp;
- }
- }
- void insertSort(int *array, int first, int last) {
- int temp;
- for(int i = 0, j; i < last; ++i) {
- temp = array[i];
- for(j = i -1; j >= 0 && array[j] > temp; --j)
- array[j+1] = array[j];
- array[j+1] = temp;
- }
- }
- TSort::TSort(int type) {
- switch(type) {
- case QUICKSORT:
- method = quickSort;
- break;
- case BUBBLESORT:
- method = bubbleSort;
- break;
- case INSERTSORT:
- method = insertSort;
- default:
- method = quickSort;
- }
- }
- void TSort::operator ()(int *array, int first, int last) {
- method(array, first, last);
- }
Advertisement
Add Comment
Please, Sign In to add comment