/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   ft_radixsort.c                                     :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: thrieg <thrieg@student.42mulhouse.fr>      +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2024/11/18 14:18:55 by alier             #+#    #+#             */
/*   Updated: 2025/02/16 19:06:42 by thrieg           ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

#include <stdlib.h>
#include <stdbool.h>
#include "ft_sorting.h"

static void	ft_naive_countsort2(struct s_countsort cs)
{
	size_t	i;

	i = cs.size - 1;
	while (true)
	{
		cs.tmp[cs.count[(cs.a[i] / cs.exp) % 10] - 1] = cs.a[i];
		cs.count[(cs.a[i] / cs.exp) % 10]--;
		if (i == 0)
			break ;
		i--;
	}
	ft_memcpy(cs.a, cs.tmp, cs.size * sizeof(*cs.a));
}

/*
 * used by `ft_naive_radixsort`
 */
static void	ft_naive_countsort(size_t size, unsigned int a[size],
							unsigned int exp)
{
	unsigned int	*tmp;
	unsigned int	count[10];
	size_t			i;

	tmp = malloc(size * sizeof(unsigned int));
	ft_bzero(count, 10 * sizeof(unsigned int));
	i = 0;
	while (i < size)
	{
		count[(a[i] / exp) % 10]++;
		i++;
	}
	i = 1;
	while (i < 10)
	{
		count[i] += count[i - 1];
		i++;
	}
	ft_naive_countsort2((struct s_countsort){size, a, exp, tmp, count});
	free(tmp);
}

/*
 * Worst-case performance:		O(size * max_digits)
 * Worst-case space complexity:	O(size + max_digits)
 */
void	ft_naive_radixsort(size_t size, unsigned int a[size])
{
	unsigned int	m;
	unsigned int	exp;

	m = ft_max_uint(size, a);
	exp = 1;
	while (m / exp > 0)
	{
		ft_naive_countsort(size, a, exp);
		exp *= 10;
	}
}
