gashink_t

сортировка вставкой

Apr 24th, 2020
151
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.11 KB | None | 0 0
  1. #include <malloc.h>
  2. #include <iostream>
  3. using namespace std;
  4.  
  5. int* create_hand(int* A, int N); // ручной ввод
  6. int* create_rand(int* A, int N); // случайный ввод
  7. void insertSort(int* a, int size);// сортировка вставкой
  8. void print(int* A, int N);
  9.  
  10. int main()
  11. {
  12.     int n = 0, c = 1; //  Размер массива
  13.     int* a = NULL; // массив чисел
  14.     cout << "Select the method for filling in the array:\n\t1)Enter the array manually;\n\t2)Array of random numbers;\n\t3)End\nYour select: ";
  15.     cin >> c;
  16.     if (c == 1)
  17.     {
  18.         cout << "\nEnter the size of the array: ";
  19.         cin >> n;
  20.         cout << "Enter your array: ";
  21.         a = create_hand(a, n);
  22.         insertSort(a, n);
  23.         cout << "Enter your sorted array: ";
  24.         print(a, n);
  25.      }
  26.     if (c == 2)
  27.     {
  28.         cout << "\nEnter the size of the array: ";
  29.         cin >> n;
  30.         a = create_rand(a, n);
  31.         cout << "Your array: ";
  32.         print(a, n);
  33.         insertSort(a, n);
  34.         cout << "Enter your sorted array: ";
  35.         print(a, n);
  36.     }
  37.         if (c == 3) c = 0;
  38.         cout << endl;
  39.     return 0;
  40. }
  41.  
  42. int* create_hand(int* A, int N)
  43. {
  44.     A = (int*)malloc(N * sizeof(int));
  45.     for (int i = 0; i < N; i++)
  46.         cin >> A[i];
  47.     return A;
  48. }
  49.  
  50. int* create_rand(int* A, int N)
  51. {
  52.     A = (int*)malloc(N * sizeof(int));
  53.     for (int i = 0; i < N; ++i)
  54.         A[i] = rand() % 100;
  55.     return A;
  56. }
  57.  
  58. void print(int* A, int N)
  59. {
  60.     for (int i = 0; i < N; i++)
  61.         cout << A[i] << " ";
  62.     cout << endl;
  63. }
  64.  
  65. void insertSort(int* a, int size)
  66. {
  67.     int tmp;
  68.     for (int i = 1, j; i < size; ++i) // цикл проходов, i - номер прохода
  69.     {
  70.         tmp = a[i];
  71.         for (j = i - 1; j >= 0 && a[j] > tmp; --j) // поиск места элемента в готовой последовательности
  72.             a[j + 1] = a[j];    // сдвигаем элемент направо, пока не дошли
  73.         a[j + 1] = tmp; // место найдено, вставить элемент    
  74.     }
  75. }
Add Comment
Please, Sign In to add comment