#include <Python.h>

// The actual sorting implementation
static PyObject* sorting_sort(PyObject* self, PyObject* args) {
    PyObject* list;
    if (!PyArg_ParseTuple(args, "O!", &PyList_Type, &list))
        return NULL;

    Py_ssize_t n = PyList_Size(list);
    for (Py_ssize_t i = 0; i < n - 1; i++) {
        for (Py_ssize_t j = 0; j < n - i - 1; j++) {
            PyObject* a = PyList_GetItem(list, j);
            PyObject* b = PyList_GetItem(list, j + 1);

            int cmp = PyObject_RichCompareBool(a, b, Py_GT);
            if (cmp == -1) return NULL;
            if (cmp) {
                Py_INCREF(a);
                Py_INCREF(b);
                PyList_SetItem(list, j, b);
                PyList_SetItem(list, j + 1, a);
                Py_DECREF(a);
                Py_DECREF(b);
            }
        }
    }
    Py_RETURN_NONE;
}

// Table of functions to export
static PyMethodDef SortingMethods[] = {
    {"sort", sorting_sort, METH_VARARGS, "Sort a Python list in place."},
    {NULL, NULL, 0, NULL}
};

// Module definition
static struct PyModuleDef sortingmodule = {
    PyModuleDef_HEAD_INIT,
    "sorting",
    NULL,
    -1,
    SortingMethods
};

// Module initialization
PyMODINIT_FUNC PyInit_sorting(void) {
    return PyModule_Create(&sortingmodule);
}
