Created
October 23, 2020 03:38
-
-
Save Alfex4936/f6fc1d2232b6d5bcaae1e79d37185149 to your computer and use it in GitHub Desktop.
Python bubble sort interface using C module
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| static PyObject *python_bubblesort(PyObject *module, PyObject *arg) | |
| { | |
| assert(arg); | |
| Py_INCREF(arg); | |
| if (!PyList_CheckExact(arg)) | |
| { | |
| PyErr_SetString(PyExc_ValueError, "Argument is not a list."); | |
| goto except; | |
| } | |
| Py_ssize_t n = PyList_Size(arg); | |
| if (n <= 1) | |
| { | |
| Py_DECREF(arg); | |
| return arg; | |
| } | |
| int isSorted = 0; | |
| int count = 0; | |
| long long *arr = (long long *)malloc(sizeof(long long) * n); | |
| for (size_t i = 0; i < n; i++) | |
| { | |
| PyObject *value = PyList_GetItem(arg, i); | |
| arr[i] = PyLong_AsLongLong(value); | |
| } | |
| while (isSorted == 0) | |
| { | |
| isSorted = 1; | |
| for (size_t i = 0; i < n - 1 - count; i++) | |
| { | |
| if (arr[i] > arr[i + 1]) | |
| { | |
| long long temp = arr[i]; | |
| arr[i] = arr[i + 1]; | |
| arr[i + 1] = temp; | |
| isSorted = 0; | |
| } | |
| } | |
| count++; | |
| } | |
| PyObject *ret = PyList_New(n); | |
| for (size_t i = 0; i != n; ++i) | |
| { | |
| PyList_SetItem(ret, i, PyLong_FromLongLong(arr[i])); | |
| } | |
| // ret = Py_BuildValue("(o)", &arr); | |
| assert(!PyErr_Occurred()); | |
| assert(ret); | |
| goto finally; | |
| except: | |
| Py_XDECREF(ret); | |
| ret = NULL; | |
| free(arr); | |
| finally: | |
| // Py_DECREF(result); | |
| Py_DECREF(arg); | |
| free(arr); | |
| return ret; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment