Быстрая сортировка

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

//Сложность по времени от O(n log(n)) до O(n^2)
//Сложность по памяти O(log(n))
//элементы меньше среднего идут влево, больше - вправо,
//затем каждая часть сортируется так же
void quickSort(int arr[], int first, int last) {
    if (first >= last) {
        return;
    }
    int i = first;
    int j = last;
    int x = arr[first + (last - first) / 2];

    while (i <= j) {
        while (arr[i] < x) {
            i++;
        }
        while (arr[j] > x) {
            j--;
        }
        if (i <= j) {
            int tmp = arr[i];
            arr[i] = arr[j];
            arr[j] = tmp;
            i++;
            j--;
        }
    }
    quickSort(arr, first, j);
    quickSort(arr, i, last);
}

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);
quickSort(sortItems, 0, (int)count - 1);
//sortItems is {1, 2, 3, 4, 5}

//qsort из библиотеки сортирует массив любого типа

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