Advertisement
haopoka

SelectionSort_Array

Apr 16th, 2020
320
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.10 KB | None | 0 0
  1. #include<iostream>
  2. #include<iomanip>
  3. #include <ctime>
  4. using namespace std;
  5.  
  6. void createArray(int arr[], int n);
  7. void Output(int arr[], int n);
  8. void SelectionSort(int arr[], int n);
  9.  
  10. int main() {
  11.     int n;
  12.     cout << "Day so nguyen co bao nhieu phan tu? (100 / 1000): ";
  13.     cin >> n;
  14.     int* arr = new int[n];
  15.     createArray(arr, n);
  16.     cout << "\nKhoi tao mang " << n << " phan tu: \n";
  17.     Output(arr, n);
  18.  
  19.     cout << "\n\nSu dung Selection Sort sap xep mang.\nMang sau khi sap xep:";
  20.     SelectionSort(arr, n);
  21.     Output(arr, n);
  22.  
  23.     return 0;
  24. }
  25.  
  26. void createArray(int arr[], int n)
  27. {
  28.     srand((int)time(NULL));
  29.     for (int i = 0; i < n;i++) {
  30.         arr[i] = rand() % 201 - 100;
  31.     }
  32. }
  33.  
  34. void Output(int arr[], int n)
  35. {
  36.     int* count = new int(0);
  37.     for (int i = 0; i < n;i++) {
  38.         if (*count % 10 == 0)
  39.             cout << endl;
  40.         cout << setw(5) << arr[i];
  41.         (*count)++;
  42.     }
  43.     delete count;
  44. }
  45.  
  46. void SelectionSort(int arr[], int n)
  47. {
  48.     int min;
  49.     for (int i = 0; i < n - 1;i++) {
  50.         min = i;
  51.         for (int j = i + 1;j < n;j++) {
  52.             if (arr[j] < arr[min])
  53.                 min = j;
  54.         }
  55.         if (min != i)
  56.             swap(arr[min], arr[i]);
  57.     }
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement