bubble sort and ...

Erdos·2024년 11월 16일
0

잡담

목록 보기
5/6

버블정렬 vs sort()비교하기

1. python 코드

import time

def bubble_sort(arr):
    n = len(arr)
    for i in range(n):
        for j in range(n - i - 1):
            if arr[j] > arr[j+1]:
                arr[j], arr[j+1] = arr[j+1], arr[j]
    return arr
    
def do_sort(arr):
    arr.sort() // timsort
    return arr

def measure_time(func, arr):
    start_time = time.time()
    result = func(arr)
    end_time = time.time()
    return end_time - start_time, result
    
arr = list(range(10000))

bubble_time, bubble_result = measure_time(bubble_sort, arr)
print("첫번째 코드 실행 시간:", format(bubble_time, ".10f"))

arr = list(range(10000))
reverse_time, reverse_result = measure_time(do_sort, arr)
print("두번째 코드 실행 시간:", format(reverse_time, ".10f"))       

2. c코드

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void bubble_sort(int *arr, int n)
{
    int i;
    
    i = 0;
    while (i < n)
    {
        int j = 0;
        while (j < n - i - 1)
        {
            if (arr[j] > arr[j + 1])
            {
                int temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
            }
            j++;
        }
        i++;
    }
}

int compare(const void *a, const void *b)
{
    return (*(int *)a - *(int *)b);
}

void do_sort(int *arr, int n)
{
    qsort(arr, n, sizeof(int), compare); // quick sort
}

void copy_array(int *src, int *dest, int n)
{
    int i = 0;
    while (i < n)
    {
        dest[i] = src[i];
        i++;
    }
}

double measure_time(void (*func)(int *, int), int *arr, int n)
{
    clock_t start_time, end_time;
    start_time = clock();
    func(arr, n);
    end_time = clock();
    return (double)(end_time - start_time) / CLOCKS_PER_SEC;
}

int main()
{
    int n = 10000;
    
    int *arr = (int *)malloc(n *sizeof(int));
    int i = 0;
    while (i < n )
    {
        arr[i]  = i;
        i++;
    }
    
    double bubble_time;
    int *bubble_arr = (int *)malloc(n * sizeof(int));
    copy_array(arr, bubble_arr, n);
    bubble_time = measure_time(bubble_sort, bubble_arr, n);
    printf("첫번째 코드 실행 시간: %.10f\n", bubble_time);
    
    double sort_time;
    int *sort_arr = (int *)malloc(n*sizeof(int));
    copy_array(arr, sort_arr, n);
    sort_time = measure_time(do_sort, sort_arr, n);
    printf("두번째 코드 실행 시간: %.10f\n", sort_time);
    
    free(arr);
    free(bubble_arr);
    free(sort_arr);
    return 0;
}
profile
수학을 사랑하는 애독자📚 Stop dreaming. Start living. - 'The Secret Life of Walter Mitty'

0개의 댓글