본문으로 바로가기

sort example not using printf

category 소식/IT 2020. 12. 12. 23:58
#include <unistd.h>
#include <stdlib.h>
#include <stdbool.h>
#include "functionPointer.h"

#define SIZE(array) sizeof(array) / sizeof(int)

bool descending(int x, int y)
{
    return (x < y);
}

bool ascending(int x, int y)
{
    return (x > y);
}

void swap(int *x, int *y)
{
    int temp;

    temp = *x;
    *x = *y;
    *y = temp;
}
void ft_putchar(char *str)
{
    while (*str)
        write(1, str++, 1);
}

int ft_len(char *str)
{
    int i;

    i = 0;
    while (str[i])
        i++;

    return (i);
}

char *ft_reverse(char *str)
{
    int i;
    int size;
    char temp;

    size = ft_len(str);
    i = 0;
    while (i < size / 2)
    {
        temp = str[i];
        str[i] = str[size - i - 1];
        str[size - i - 1] = temp;
        i++;
    }
    return (str);
}

void sort(int *array, int size, bool (*comparisonFnc)(int, int))
{
    for (int i = 0; i < size - 1; i++)
    {
        for (int j = 0; j < size - i - 1; j++)
        {
            if (comparisonFnc(array[j], array[j + 1]))
                swap(&array[j], &array[j + 1]);
        }
    }
};

int ft_size(int integer)
{
    int i;

    i = 0;
    while (integer > 0)
    {
        integer /= 10;
        i++;
    }
    return (i);
}

char *ft_itoa(int integer)
{
    int nbr;
    bool negative;
    char *result;
    int i;

    negative = false;
    nbr = integer;
    if (nbr < 0)
    {
        nbr = -nbr;
        negative = true;
    }
    result = (char *)malloc(sizeof(char) * ft_size(nbr) + 2);

    i = 0;
    while (nbr > 0)
    {
        result[i++] = (nbr % 10) + 48;
        nbr /= 10;
    }
    if (negative)
        result[i++] = '-';
    result[i] = '\0';
    result = ft_reverse(result);
    return (result);
}

void ft_print_result(int *arr, int size)
{
    for (int i = 0; i < size; i++)
    {
        ft_putchar(ft_itoa(arr[i]));
        ft_putchar(" ");
    }
    ft_putchar("\n");
}

int main(void)
{
    int arr[10] = {10, 2, 8, 6, 1, -3, 4, 7, 5, 9};
    int size;
    size = SIZE(arr);
    sort(arr, size, descending);
    ft_print_result(arr, size);
    sort(arr, size, ascending);
    ft_print_result(arr, size);
    return (0);
}
void sort(int* array, int size, bool (*comparisonFnc)(int, int));
bool descending(int x, int y);
bool ascending(int x, int y); 
void swap(int *x, int *y);

'소식 > IT' 카테고리의 다른 글

배민 테크코스 1기 코딩테스트 지원  (1) 2019.03.15
첫 게시글입니다.  (2) 2019.03.09