Repository navigation
Expand file tree
/
Copy pathft_sort_str_array.c
More file actions
67 lines (62 loc) · 2.27 KB
/
Copy pathft_sort_str_array.c
File metadata and controls
67 lines (62 loc) · 2.27 KB
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
60
61
62
63
64
65
66
67
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_sort_str_array.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: guiricha <guiricha@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/10/19 14:22:02 by guiricha #+# #+# */
/* Updated: 2018/06/06 12:55:04 by guiricha ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
#include <stdlib.h>
static void order_indexes_correctly(char **array, int *array_indexes, int (*f)(const char *s1, const char*s2), char asc)
{
int index;
int result_of_cmp;
int tmpind;
index = 0;
while (array_indexes[index + 1] != -1)
{
if ((result_of_cmp =
f(array[array_indexes[index]],
array[array_indexes[index + 1]])) != 0)
{
if ((asc && result_of_cmp > 0) || (!asc && result_of_cmp < 0))
{
tmpind = array_indexes[index];
array_indexes[index] = array_indexes[index + 1];
array_indexes[index + 1] = tmpind;
index = 0;
continue ;
}
}
index++;
}
}
char **ft_sort_str_array(char **array, int array_len, int (*f)(const char *s1, const char*s2), char ascending)
{
int *array_indexes;
int index;
char **ret_array;
if (array_len < 2 || !array)
return (array);
array_indexes = (int *)malloc(sizeof(int) * array_len + 1);
array_indexes[array_len] = -1;
index = -1;
while (++index < array_len)
array_indexes[index] = index;
order_indexes_correctly(array, array_indexes, f, ascending);
ret_array = (char **)malloc(sizeof(char *) * (array_len + 1));
ret_array[array_len] = NULL;
index = -1;
while (array_indexes[++index] != -1)
{
ret_array[index] = (char *)malloc(sizeof(char) *
ft_strlen(array[array_indexes[index]]) + 1);
ft_strcpy(ret_array[index], array[array_indexes[index]]);
}
free(array_indexes);
return (ret_array);
}