dzungchaos

C++ "Sắp xếp Selection"

Nov 6th, 2019
156
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.08 KB | None | 0 0
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. void selection_sort(int *a, int n, int order){
  5.     for (int i = order + 1; i < n; i++) {
  6.         for (int j = i - 1; j >= 0; j--) {
  7.            
  8.             if (a[i] >= a[j]) {
  9.                 cout <<a[j] <<endl;
  10.                 for (int k = i; k > j + 1; k--) {
  11.                     cout<<a[k - 1] <<" ";
  12.                     a[k] = a[k - 1];
  13.                 }
  14.                 a[j + 1] = a[i];
  15.                 break; 
  16.             }
  17.            
  18.             if (j == 0) {
  19.                 for (int k = i; k > 0; k--) {
  20.                     a[k] = a[k - 1];
  21.                 }
  22.                 a[0] = a[i];
  23.             }
  24.         }
  25.     }
  26.    
  27. }
  28.  
  29. int findOrder(int *a, int n) {
  30.     for (int i = 0; i < n; i++) {
  31.         if (a[i] > a[i + 1]) {
  32.             return i;
  33.         }
  34.     }
  35. }
  36.  
  37. int main(){
  38.     int n, *a;
  39.     do{
  40.         cout << "Nhap n = ";
  41.         cin >> n;
  42.         if (n <= 0)
  43.             cout << "Phai nhap n > 0 !" << endl;
  44.     } while (n <= 0);
  45.     a = new int[n];
  46.  
  47.     // Nhap cac phan tu cua mang
  48.     for(int i = 0; i < n; i++){
  49.         cout << "a[" << i << "] = ";
  50.         cin >> a[i];
  51.     }
  52.     // Sap xep
  53.     buble_sort(a, n);
  54.  
  55.     int order = findOrder(a, n);
  56.     selection_sort(a, n, order);
  57.    
  58.     for (int i = 0; i < n; i++) {
  59.         cout << *(a + i) <<" ";
  60.     }
  61.     // Giai phong bo nho
  62.     delete[] a;
  63.     return 0;
  64. }
Advertisement
Add Comment
Please, Sign In to add comment