minishell
ft_qsort.c
Go to the documentation of this file.
1 /* ************************************************************************** */
2 /* */
3 /* ::: :::::::: */
4 /* ft_qsort.c :+: :+: :+: */
5 /* +:+ +:+ +:+ */
6 /* By: kfujita <kfujita@student.42tokyo.jp> +#+ +:+ +#+ */
7 /* +#+#+#+#+#+ +#+ */
8 /* Created: 2023/02/18 23:48:10 by kfujita #+# #+# */
9 /* Updated: 2023/03/02 11:24:24 by kfujita ### ########.fr */
10 /* */
11 /* ************************************************************************** */
12 
13 #include "ft_sort.h"
14 #include "../ft_mem/ft_mem.h"
15 
16 #include "../ft_math/ft_math.h"
17 
18 // ref: http://www.math.u-ryukyu.ac.jp/~suga/C/2004/13/node6.html
19 
20 unsigned char *_at(unsigned char *base, size_t i, size_t memb_size)
21 {
22  return (base + (i * memb_size));
23 }
24 
25 void _ft_qsort(unsigned char *base, size_t nmemb, size_t memb_size,
26  t_compar compar)
27 {
28  size_t i;
29  size_t i_last;
30 
31  if (base == NULL || nmemb <= 1 || memb_size <= 0 || compar == NULL)
32  return ;
33  i = 1;
34  i_last = 0;
35  while (i < nmemb)
36  {
37  if (0 < compar(base, _at(base, i, memb_size)))
38  ft_swap(_at(base, i, memb_size),
39  _at(base, ++i_last, memb_size), memb_size);
40  i++;
41  }
42  ft_swap(base, _at(base, i_last, memb_size), memb_size);
43  if (2 <= i_last)
44  _ft_qsort(base, i_last, memb_size, compar);
45  if (2 <= (nmemb - i_last - 1))
46  _ft_qsort(_at(base, i_last + 1, memb_size), nmemb - i_last - 1,
47  memb_size, compar);
48 }
49 
50 bool ft_qsort(void *base, size_t nmemb, size_t memb_size, t_compar compar)
51 {
52  if (!can_mulp(nmemb, memb_size))
53  return (false);
54  _ft_qsort((unsigned char *)base, nmemb, memb_size, compar);
55  return (true);
56 }
bool can_mulp(size_t a, size_t b)
Definition: can_mul.c:50
void ft_swap(void *a, void *b, size_t bytes)
Definition: ft_swap.c:32
bool ft_qsort(void *base, size_t nmemb, size_t memb_size, t_compar compar)
Definition: ft_qsort.c:50
void _ft_qsort(unsigned char *base, size_t nmemb, size_t memb_size, t_compar compar)
Definition: ft_qsort.c:25
unsigned char * _at(unsigned char *base, size_t i, size_t memb_size)
Definition: ft_qsort.c:20
int(* t_compar)(const void *, const void *)
Definition: ft_sort.h:22