-
Notifications
You must be signed in to change notification settings - Fork 0
/
vec_quicksort.c
79 lines (70 loc) · 1.94 KB
/
vec_quicksort.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* vec_quicksort.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: toramo <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/01/02 10:49:42 by toramo #+# #+# */
/* Updated: 2024/01/02 10:49:42 by toramo ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static void memswap8(unsigned char *a, unsigned char *b)
{
if (a == b)
return ;
*a ^= *b;
*b ^= *a;
*a ^= *b;
}
static void memswap(unsigned char *a, unsigned char *b, size_t bytes)
{
size_t i;
if (!a || !b)
return ;
i = 0;
while (i < bytes)
{
memswap8(&a[i], &b[i]);
i++;
}
}
static size_t vec_partition(t_vec *src, int low,
int high, int (*f)(void *, void *))
{
void *pivot;
int i;
int j;
pivot = vec_get(src, high);
i = low - 1;
j = low;
while (j < high)
{
if (f(vec_get(src, j), pivot) <= 0)
{
i++;
memswap(vec_get(src, i), vec_get(src, j), src->elem_size);
}
j++;
}
i++;
memswap(vec_get(src, i), pivot, src->elem_size);
return (i);
}
static void vec_quicksort(t_vec *src, int low,
int high, int (*f)(void *, void *))
{
int p;
if (low >= high || low < 0)
return ;
p = vec_partition(src, low, high, f);
vec_quicksort(src, low, p - 1, f);
vec_quicksort(src, p + 1, high, f);
}
void vec_sort(t_vec *src, int (*f)(void *, void *))
{
if (!src || !src->memory)
return ;
vec_quicksort(src, 0, src->len - 1, f);
}