dzungchaos

C++ "Sắp xếp Bubble + Swap"

Nov 6th, 2019
135
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.68 KB | None | 0 0
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. void swap (int *a, int i, int j){
  5.     int temp = a[i]; // a[i] = *(a + 1)
  6.     a[i] = a[j];
  7.     a[j] = temp;
  8. }
  9.  
  10. void bubble_sort(int *a, int n){
  11.     for (int i = 0; i < n -1; i++){
  12.         for (int j = i + 1; j < n; j++){
  13.             if (a[i] < a[j])
  14.             swap (a, i ,j);
  15.         }  
  16.     }
  17. }
  18.  
  19. int main(){
  20.     int n, *a, tg;
  21.     do{
  22.         cout << "Nhap n vao ";
  23.         cin >> n;
  24.         if (n < 0)
  25.             cout << "Phai nhap n > 0!" << endl;
  26.     } while (n <= 0);
  27.    
  28.     a = new int[n];
  29.    
  30.     for(int i = 0; i < n; i++){
  31.         cout << "a[" << i + 1 << "] = ";
  32.         cin >> a[i];
  33.        
  34.     }
  35.    
  36.    
  37.     bubble_sort(a, n);
  38.  
  39.    
  40.     for (int i = 0; i < n; i++){
  41.         cout << a[i] << " ";
  42.         }
  43.        
  44.     delete[] a;
  45.     return 0;
  46. }
Advertisement
Add Comment
Please, Sign In to add comment