模拟qsort函数

#include 
#include 
#include 

typedef int (*compare_func)(const void*, const void*);

void my_qsort(void* base, size_t num, size_t size, compare_func compare) {
    char* arr = (char*)base;
    for (size_t i = 0; i < num - 1; i++) {
        for (size_t j = 0; j < num - 1 - i; j++) {
            char* a = arr + j * size;
            char* b = arr + (j + 1) * size;
            if (compare(a, b) > 0) {
                for (size_t k = 0; k < size; k++) {
                    char temp = a[k];
                    a[k] = b[k];
                    b[k] = temp;
                }
            }
        }
    }
}

int compare_int(const void* a, const void* b) {
    return (*(int*)a - *(int*)b);
}

int main() {
    int nums[10] = { 9, 2, 5, 1, 7, 4, 6, 3, 10, 8 };
    size_t size = sizeof(nums) / sizeof(nums[0]);

    my_qsort(nums, size, sizeof(nums[0]), compare_int);

    printf("排序后的数组:");
    for (size_t i = 0; i < size; i++) {
        printf("%d ", nums[i]);
    }
    printf("\n");

    return 0;
}

你可能感兴趣的:(c++,算法,数据结构)