c++ - Sort and Swap using byte pointers to array types -
i'm trying sort arrays using byte pointers.. this, mean don't want know given type of array. sort of generic-sort without templates.
so far, algorithm (bubble sort) seems working sorting integer arrays. however, cannot figure out why same algorithm won't sort char or float arrays.. took algorithm old post wrote solution being: http://ideone.com/uagogp , changed use bytes instead..
any ideas i'm doing wrong?
#include <iostream> template<typename t> void print(t* arr, std::size_t size) { std::cout<<"["; (std::size_t = 0; < size - 1; ++i) { std::cout<<arr[i]<<" "; } std::cout<<arr[size - 1]<<"]\n"; } void ptrswap(std::uint8_t* a, std::uint8_t* b, std::size_t size_ptr) { std::uint8_t t = 0; (int = 0; < size_ptr; ++i) { t = a[i]; a[i] = b[i]; b[i] = t; } } void ptrsort(std::uint8_t* list, std::size_t length, std::size_t size_ptr, bool (*comparator)(void* a, void* b)) { int size = length * size_ptr; (std::size_t = 0; < size; += size_ptr) { (std::size_t j = 0; j < size - - size_ptr; j += size_ptr) { if (comparator(&list[j + size_ptr], &list[j])) { ptrswap(&list[j + size_ptr], &list[j], size_ptr); } } } } bool intcomparator(void* a, void* b) { return *static_cast<int*>(a) < *static_cast<int*>(b); } bool charcomparator(void* a, void* b) { return *static_cast<char*>(a) < *static_cast<char*>(b); } bool floatcomparator(void* a, void* b) { return *static_cast<float*>(a) < *static_cast<float*>(b); } int main() { int arr[] = {1, 3, 9, 7, 2, 4, 10, 6, 5, 8}; ptrsort((std::uint8_t*)&arr[0], 10, sizeof(int), &intcomparator); print(arr, 10); char arr2[] = {'a', 'j', 'c', 'i', 'h', 'g', 'd', 'e', 'b', 'f'}; ptrsort((std::uint8_t*)&arr2[0], 10, sizeof(char), &charcomparator); print(arr2, 10); float arr3[] = {1.0, 1.3, 1.9, 1.7, 1.2, 1.4, 1.1, 1.6, 1.5, 1.8}; ptrsort((std::uint8_t*)&arr3[0], 10, sizeof(float), &floatcomparator); print(arr3, 10); } edit: solved.. above code work.
Comments
Post a Comment