thespeedracer38

Function template Bubble Sort

Mar 18th, 2019
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.16 KB | None | 0 0
  1. #include <iostream>
  2. #include <cstdlib>
  3.  
  4. using namespace std;
  5.  
  6. template <class T>
  7. void bubbleSort(T arr[], int size){
  8.     bool flag = true;
  9.     for(int i = 0; (i < size-1) && flag; i++){
  10.         flag = false;
  11.         for(int j = 0; j < size-i-1; j++){
  12.             if(arr[j] > arr[j + 1]){
  13.                 T temp = arr[j];
  14.                 arr[j] = arr[j + 1];
  15.                 arr[j + 1] = temp;
  16.                 flag = true;
  17.             }
  18.         }
  19.     }
  20. }
  21.  
  22. template <class T>
  23. void display(T arr[], int size){
  24.     for(int i = 0; i < size; i++){
  25.         cout << arr[i] << ", ";
  26.     }
  27.     cout << endl;
  28. }
  29.  
  30. template <class T>
  31. void input(T arr[], int size){
  32.     for(int i = 0; i < size; i++){
  33.         cout << "arr[" << i << "] = ";
  34.         cin >> arr[i];
  35.     }
  36. }
  37.  
  38. int main() {
  39.     system("cls");
  40.    
  41.     int arr1[] = {38, 41, 56, 32, 14, 22};
  42.     double arr2[] = {1.2, 7.4, 3.3, 7.4, 6.93};
  43.     int size1 = sizeof(arr1) / sizeof(arr1[0]);
  44.     int size2 = sizeof(arr2) / sizeof(arr2[0]);
  45.    
  46.     cout << "Before sorting\n";
  47.     display(arr1, size1);
  48.     bubbleSort(arr1, size1);
  49.     cout << "After sorting\n";
  50.     display(arr1, size1);
  51.    
  52.     cout << endl;
  53.    
  54.     cout << "Before sorting\n";
  55.     display(arr2, size2);
  56.     bubbleSort(arr2, size2);
  57.     cout << "After sorting\n";
  58.     display(arr2, size2);
  59.    
  60.     return 0;
  61. }
Add Comment
Please, Sign In to add comment