Сортировка пузырьком

Алгоритмы / Сортировка

//Сложность по времени O(n^2)
//Сложность по памяти O(1)
//соседние элементы меняются местами, пока не выйдет проход без обменов:
//наибольший элемент на каждом проходе уходит в конец ("bubbles up")
void bubbleSort(int arr[], size_t count) {
    for (size_t end = count; end > 1; end--) {
        bool swapped = false;
        for (size_t j = 1; j < end; j++) {
            if (arr[j] < arr[j - 1]) {
                int tmp = arr[j];
                arr[j] = arr[j - 1];
                arr[j - 1] = tmp;
                swapped = true;
            }
        }
        if (!swapped) {
            break;
        }
    }
}

void printArray(const char *name, const int arr[], size_t count) {
    printf("%s is {", name);
    for (size_t i = 0; i < count; i++) {
        if (i > 0) {
            printf(", ");
        }
        printf("%d", arr[i]);
    }
    printf("}\n");
}

int items[] = {4, 1, 5, 3, 2};
size_t count = sizeof items / sizeof items[0];

//сортировка работает на месте: копия сохраняет items как есть
int sortItems[5];
memcpy(sortItems, items, sizeof items);
bubbleSort(sortItems, count);
//sortItems is {1, 2, 3, 4, 5}

printArray("items", items, count);
printArray("sortItems", sortItems, count);