Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <time.h>
- #include <string.h>
- // формирует массив по возрастанию
- int* arr_up(int n) {
- int* result = (int*)malloc(sizeof(int) * n);
- for (int i = 0; i < n; i++)
- result[i] = i + 1;
- return result;
- }
- // формирует массив по уменьшению
- int* arr_down(int n) {
- int* result = (int*)malloc(sizeof(int) * n);
- for (int i = n - 1; i >= 0; i--)
- result[n - 1 - i] = i + 1;
- return result;
- }
- // формирует массив из рандомных элементов
- int* arr_rand(int n) {
- int* result = (int*)malloc(sizeof(int) * n);
- for (int i = 0; i < n; i++)
- result[i] = rand() % 100;
- return result;
- }
- // алгоритм быстрой сортировки
- unsigned long long qsortRecursive(int* mas, int size) {
- unsigned long long counter = 0;
- int i = 0; // начало массива
- int j = size - 1; // конец
- int mid = mas[size / 2]; // середина
- // смотрим лево право, разбиваем его на ещё меньшие пропорции и меняем местами
- do {
- while (mas[i] < mid) {
- i++;
- counter++;
- }
- while (mas[j] > mid) {
- j--;
- counter++;
- }
- if (i <= j) {
- int tmp = mas[i];
- mas[i] = mas[j];
- mas[j] = tmp;
- counter++;
- i++;
- j--;
- }
- } while (i <= j);
- if (j > 0) {
- counter += qsortRecursive(mas, j + 1);
- }
- if (i < size) {
- counter += qsortRecursive(&mas[i], size - i);
- }
- return counter;
- }
- // алгоритм бинарных вставок
- unsigned long long BinSort(int* mas, int n) {
- int key, low, hight, mid;
- unsigned long long count = 0;
- for (int i = 1; i < n; i++) {
- key = mas[i];
- low = 0; hight = i - 1;
- while (low < hight) {
- mid = low + (hight - low) / 2;
- if (key < mas[mid])
- hight = mid;
- else
- low = mid + 1;
- count++;
- }
- for (int j = i; j < low + 1; j--) {
- mas[j] = mas[j - 1];
- count++;
- }
- mas[low] = key;
- count++;
- }
- return count;
- }
- void main() {
- srand(time(NULL));
- FILE* f;
- fopen_s(&f, "result.txt", "w+");
- for (int n = 500; n <= 50000; n += 500) {
- int* arr = (int*)malloc(sizeof(int) * n);
- int* arr1 = (int*)malloc(sizeof(int) * n);
- unsigned long long result[6];
- arr = arr_up(n);
- result[0] = BinSort(arr, n); // по возраст, бин сортировка
- result[3] = qsortRecursive(arr, n); // по возраст, быстрая сорт
- arr = arr_down(n);
- result[2] = BinSort(arr, n); // по уменьше, бин сорт
- arr = arr_down(n);
- result[5] = qsortRecursive(arr, n); // по уменьше, быстрая сорт
- unsigned long long summ = 0, summm = 0; // для бинарной и быстрой
- for (int i = 0; i < 100; i++) {
- arr = arr_rand(n);
- memcpy(arr1, arr, sizeof(arr));
- summ += BinSort(arr, n);
- summm += qsortRecursive(arr1, n);
- }
- result[1] = summ / 100; // ранд, бин сорт
- result[4] = summm / 100; // ранд, быстрая сорт
- printf("%d\n", n);
- fprintf(f, "%d %llu %llu %llu %llu %llu %llu\n", n, result[0], result[1], result[2],
- result[3], result[4], result[5]);
- }
- fclose(f);
- return;
- }
Add Comment
Please, Sign In to add comment