aboutsummaryrefslogtreecommitdiff
path: root/functions_reference/ref_ft_list_sort.c
blob: 6f405136fd11c9fbde1b6581df341d93a8e20ae6 (plain)
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
/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   ref_ft_list_sort.c                                 :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: cacharle <marvin@42.fr>                    +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2020/02/08 02:49:28 by cacharle          #+#    #+#             */
/*   Updated: 2020/11/07 17:17:13 by charles          ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

#include "libasm_test.h"

static
t_list* merge_sorted_list(t_list* l1, t_list* l2, int (*cmp)(void *, void*))
{
	t_list *merged = 0x0;

	if (l1 == 0x0)
		return l2;
	if (l2 == 0x0)
		return l1;
	if (cmp(l1->data, l2->data) < 0)
	{
		merged = l1;
		merged->next = merge_sorted_list(l1->next, l2, cmp);
	}
	else
	{
		merged = l2;
		merged->next = merge_sorted_list(l1, l2->next, cmp);
	}
	return merged;
}

void ref_ft_list_sort(t_list **begin_list, int (*cmp)(void *, void*))
{
	if (begin_list == 0x0 || *begin_list == 0x0
			|| (*begin_list)->next == 0x0)
		return ;
	t_list *fast = (*begin_list)->next;
	t_list *slow = *begin_list;
	while (fast != 0x0)
	{
		fast = fast->next;
		if (fast != 0x0)
		{
			fast = fast->next;
			slow = slow->next;
		}
	}
	t_list *middle = slow->next;
	slow->next = 0x0;

	ref_ft_list_sort(begin_list, cmp);
	ref_ft_list_sort(&middle, cmp);
	*begin_list = merge_sorted_list(*begin_list, middle, cmp);
}