diff --git a/src/hw4_optimalSort/CMakeLists.txt b/src/hw4_optimalSort/CMakeLists.txt new file mode 100644 index 0000000..504dfb1 --- /dev/null +++ b/src/hw4_optimalSort/CMakeLists.txt @@ -0,0 +1,9 @@ +cmake_minimum_required(VERSION 4.0) +project(hw4_optimalSort C) + +set(CMAKE_C_STANDARD 17) + +add_executable(hw4_optimalSort + main.c + sort.c +) diff --git a/src/hw4_optimalSort/README.md b/src/hw4_optimalSort/README.md new file mode 100644 index 0000000..398d176 --- /dev/null +++ b/src/hw4_optimalSort/README.md @@ -0,0 +1,12 @@ +# Код на С для домашней работы "Оптимальная" сортировка. +Здесь четыре файла - один main с чтением вводимых чисел, и во втором сортировка пузырьком (для вводимых данных в количестве 100 штук О(n^2) будет быстрым) и заголовочный файл sort.h, а также CMake для сборки без ассемблера + +# Запуск: (с созданием ассемлерного файла с оптимизацией О2) +gcc -S -O2 sort.c -o sort.s && gcc -c main.c -o main.o && gcc -c sort.s -o sort.o && gcc main.o sort.o -o sorterWithASM +./sorterWithASM +10 1 9 -1 0 6 #Вводим до 100 чисел и затем завершаем ввод сочетанием Ctrl+D + +# Запуск через CMake: +cmake -B build && cmake --build build +./build/hw4_optimalSort +10 1 9 -1 0 6 #Вводим до 100 чисел и затем завершаем ввод сочетанием Ctrl+D diff --git a/src/hw4_optimalSort/main.c b/src/hw4_optimalSort/main.c new file mode 100644 index 0000000..207606c --- /dev/null +++ b/src/hw4_optimalSort/main.c @@ -0,0 +1,23 @@ +#include +#include "sort.h" + +int main() +{ + int array[100]; + int count = 0; + + while (count < 100 && scanf("%d", &array[count]) == 1) { + count++; + } + + int moved = sortArray(array, count); + + for (int i = 0; i < count; i++) { + // Чтоб удобнее глазками считать колво перестановок + printf("%d ", array[i]); + } + printf("\n"); + + printf("%d ", moved); + return moved; +} diff --git a/src/hw4_optimalSort/sort.c b/src/hw4_optimalSort/sort.c new file mode 100644 index 0000000..267970d --- /dev/null +++ b/src/hw4_optimalSort/sort.c @@ -0,0 +1,36 @@ +#include "sort.h" + +int sortArray(int array[], int count) +{ + int movedCount = 0; + + // Копия массива + int original[100]; + for (int i = 0; i < count; i++) { + original[i] = array[i]; + } + + for (int i = 0; i < count - 1; i++) { + int swapped = 0; + for (int j = 0; j < count - i - 1; j++) { + if (array[j] > array[j + 1]) { + int temp = array[j]; + array[j] = array[j + 1]; + array[j + 1] = temp; + swapped = 1; + } + } + if (!swapped) { + break; + } + } + + for (int i = 0; i < count; i++) { + if (array[i] != original[i]) { + movedCount++; + } + } + + return movedCount; +} + diff --git a/src/hw4_optimalSort/sort.h b/src/hw4_optimalSort/sort.h new file mode 100644 index 0000000..6ab74a9 --- /dev/null +++ b/src/hw4_optimalSort/sort.h @@ -0,0 +1,3 @@ +#pragma once + +int sortArray(int array[], int count);