aboutsummaryrefslogtreecommitdiff
path: root/src/lst/ft_lstsort.c
blob: 9945a0f8db95f68d9c9d9c3c5bd6b51b2981abc2 (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
/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   ft_lstsort.c                                       :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: cacharle <marvin@42.fr>                    +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2020/02/10 01:53:55 by cacharle          #+#    #+#             */
/*   Updated: 2020/02/16 02:18:05 by cacharle         ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

#include "libft_lst.h"

/*
** \brief      Sort list
** \param cmp  Comparison function, <0 if less, 0 if equal, >0 if greater
** \note       Use merge sort algorithm
*/

void	ft_lstsort(t_ftlst **begin_list, t_ftcompar_func cmp)
{
	t_ftlst	*fast;
	t_ftlst	*slow;
	t_ftlst	*middle;

	if (begin_list == NULL || *begin_list == NULL
			|| (*begin_list)->next == NULL)
		return ;
	fast = (*begin_list)->next;
	slow = *begin_list;
	while (fast != NULL)
	{
		fast = fast->next;
		if (fast != NULL)
		{
			fast = fast->next;
			slow = slow->next;
		}
	}
	middle = slow->next;
	slow->next = NULL;
	ft_lstsort(begin_list, cmp);
	ft_lstsort(&middle, cmp);
	*begin_list = ft_lstsorted_merge(*begin_list, middle, cmp);
}