Advertisement
nadya_misheva

bubble selection

Mar 17th, 2023
390
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.47 KB | None | 0 0
  1.  
  2. #include <iostream>
  3.  
  4. using namespace std;
  5.  
  6. int as = 0;
  7. int comp = 0;
  8.  
  9.  
  10. void selection_sort(int a[], int n){
  11.     int min;
  12.     int i, j;
  13.     for(i = 0; i < n-1; i++){
  14.        
  15.         int minInd = i;
  16.         for(j = i+1; j < n; j++){
  17.             comp++;
  18.             if(a[j]<a[minInd]) minInd = j;
  19.         }
  20.         if(minInd!=i){
  21.         as++;
  22.         a[i] = a[i]^a[minInd];
  23.         a[minInd] = a[i]^a[minInd];
  24.         a[i] = a[i]^a[minInd];
  25.         }
  26.     }
  27. }
  28.  
  29. void bubble_sort(int a[], int n){
  30.     int i, j;
  31.     bool swapped;
  32.     for(i = n-2; i >= 0; i--){
  33.         swapped = false;
  34.         for(j = 0; j <=i; j++){
  35.             comp++;
  36.             if(a[j] > a[j+1]){
  37.                 as++;
  38.                 a[j]  = a[j] ^ a[j+1];
  39.                 a[j+1]  = a[j] ^ a[j+1];
  40.                 a[j]  = a[j] ^ a[j+1];
  41.                 swapped = true;
  42.             }
  43.         }
  44.         if(swapped==false) break;
  45.     }
  46. }
  47.  
  48.  
  49.  
  50. int main()
  51. {
  52.     int arr[] = {1,3,5,6,4,2};
  53.     int sz = 7;
  54.    
  55.     selection_sort(arr,sz);
  56.     cout << "selection_sort" << endl;
  57.     for(int i = 0; i < sz; i++){
  58.         cout << arr[i];
  59.     }
  60.    
  61.     cout << "\nas = " << as << " comp = " << comp << endl;
  62.  
  63.     as = 0;
  64.     comp = 0;
  65.    
  66.      int arr1[] = {1,3,5,6,4,2};
  67.     cout << "bubble_sort" << endl;
  68.     bubble_sort(arr1,sz);
  69.     for(int i = 0; i < sz; i++){
  70.         cout << arr[i];
  71.     }
  72.     cout << "\nas = " << as << " comp = " << comp << endl;
  73.     return 0;
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement