Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
Path: blob/master/libraries/AP_Common/sorting.cpp
Views: 1798
/*1This program is free software: you can redistribute it and/or modify2it under the terms of the GNU General Public License as published by3the Free Software Foundation, either version 3 of the License, or4(at your option) any later version.56This program is distributed in the hope that it will be useful,7but WITHOUT ANY WARRANTY; without even the implied warranty of8MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the9GNU General Public License for more details.1011You should have received a copy of the GNU General Public License12along with this program. If not, see <http://www.gnu.org/licenses/>.13*/1415#include <stdint.h>16#include "sorting.h"1718/*19in-place insertion sort for small arrays of data. This is O(n) if20already sorted and O(n^2) for worst case (elements are reversed)21sort order is smallest first22*/23void insertion_sort_uint16(uint16_t *data, uint16_t n)24{25for (uint16_t i=1; i<n; i++) {26uint16_t temp = data[i];27int16_t j = i - 1;2829while (j >= 0 && data[j] > temp) {30data[j+1] = data[j];31j--;32}33data[j+1] = temp;34}35}3637/*38remove duplicates from a sorted uint16_t array, returning the new39count40*/41uint16_t remove_duplicates_uint16(uint16_t *data, uint16_t n)42{43uint16_t removed = 0;44for (uint16_t i=1; i<n; i++) {45if (data[i-(1+removed)] == data[i]) {46removed++;47} else if (removed != 0) {48data[i-removed] = data[i];49}50}51return n - removed;52}5354/*55bisection search on a sorted uint16_t array to find an element56return true if found57*/58bool bisect_search_uint16(const uint16_t *data, uint16_t n, uint16_t value)59{60if (n == 0) {61return false;62}63uint16_t low=0, high=n-1;64while (low < high) {65uint16_t mid = (low+high)/2;66if (value < data[mid]) {67high = mid;68continue;69}70if (value > data[mid]) {71low = mid+1;72continue;73}74return true;75}76return data[low] == value;77}7879/*80remove elements in a 2nd sorted array from a sorted uint16_t array81return the number of remaining elements82*/83uint16_t remove_list_uint16(uint16_t *data, uint16_t n, const uint16_t *rem, uint16_t n2)84{85uint16_t removed = 0;86for (uint16_t i=0; i<n; i++) {87if (bisect_search_uint16(rem, n2, data[i])) {88removed++;89} else if (removed != 0) {90data[i-removed] = data[i];91}92}93return n - removed;94}9596/*97return number of common elements between two sorted uint16_t lists98*/99uint16_t common_list_uint16(uint16_t *data, uint16_t n, const uint16_t *data2, uint16_t n2)100{101uint16_t common = 0;102for (uint8_t i=0; i<n2; i++) {103if (bisect_search_uint16(data, n, data2[i])) {104common++;105}106}107return common;108}109110111