data_structures
min_pq_pop.c
Go to the documentation of this file.
1 /* ************************************************************************** */
3 /* */
4 /* ::: :::::::: */
5 /* min_pq_pop.c :+: :+: :+: */
6 /* +:+ +:+ +:+ */
7 /* By: unite <marvin@42.fr> +#+ +:+ +#+ */
8 /* +#+#+#+#+#+ +#+ */
9 /* Created: 2020/07/17 14:23:02 by unite #+# #+# */
10 /* Updated: 2020/09/01 20:12:39 by unite ### ########.fr */
11 /* */
12 /* ************************************************************************** */
13 
14 #include "min_pq.h"
15 
16 static void min_pq_sink(t_min_pq *pq, size_t k)
17 {
18  size_t j;
19 
20  while (2 * k <= array_size(pq))
21  {
22  j = 2 * k;
23  if (j < array_size(pq) &&
24  pq->type->cmp(
25  array_get(pq, j - 1),
26  array_get(pq, j)) > 0)
27  j++;
28  if (pq->type->cmp(
29  array_get(pq, k - 1),
30  array_get(pq, j - 1)) > 0)
31  array_swap(pq, k - 1, j - 1);
32  else
33  break ;
34  k = j;
35  }
36 }
37 
38 void *min_pq_pop(t_min_pq *pq)
39 {
40  void *min;
41 
42  array_swap(pq, 0, array_size(pq) - 1);
43  min = array_pop(pq);
44  min_pq_sink(pq, 1);
45  return (min);
46 }
array_get
void * array_get(const t_array *array, size_t index)
Returns the item at the specified position in this list.
Definition: array_get.c:16
array_size
size_t array_size(const t_array *array)
Returns the number of elements in this array.
Definition: array_size.c:16
s_type::cmp
int(* cmp)(const void *, const void *)
(optional) A function ponter used to compare members of this data type
Definition: types.h:52
array_swap
void array_swap(t_array *array, size_t ind1, size_t ind2)
Swaps elements at the two specified positions in the array.
Definition: array_swap.c:16
array_pop
void * array_pop(t_array *array)
Removes and returns the element at the end of this array.
Definition: array_pop.c:17
min_pq.h
s_array::type
const t_type * type
The type of items in this array.
Definition: array.h:52
s_array
A resizable array.
Definition: array.h:47
min_pq_pop
void * min_pq_pop(t_min_pq *pq)
Removes and returns the smallest key in this queue.
Definition: min_pq_pop.c:38