some new stuff.
idk its all pretty fun! some C++ too!
This commit is contained in:
10
simulations/sorting_quicksort/setup.py
Normal file
10
simulations/sorting_quicksort/setup.py
Normal file
@@ -0,0 +1,10 @@
|
||||
from setuptools import setup, Extension
|
||||
|
||||
module = Extension("sorting", sources=["sorting.c"])
|
||||
|
||||
setup(
|
||||
name="sorting",
|
||||
version="1.0",
|
||||
description="Simple C sorting extension",
|
||||
ext_modules=[module],
|
||||
)
|
||||
48
simulations/sorting_quicksort/sorting.c
Normal file
48
simulations/sorting_quicksort/sorting.c
Normal file
@@ -0,0 +1,48 @@
|
||||
#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);
|
||||
}
|
||||
4
simulations/sorting_quicksort/sorting.py
Normal file
4
simulations/sorting_quicksort/sorting.py
Normal file
@@ -0,0 +1,4 @@
|
||||
import sorting
|
||||
arr = [5, 3, 8, 1, 2]
|
||||
sorting.sorting(arr)
|
||||
print(arr)
|
||||
Reference in New Issue
Block a user