본문 바로가기
C and C++/C and C++ Examples

[C Examples] 버블 정렬 (Bubble sort)을 활용해서 티켓 추첨하기

by Henry Cho 2023. 12. 4.
728x90

버블 정렬 (Bubble sort)을 활용해서 티켓 추첨하기

포스트 난이도: HOO_Junior


# Example Code

이번 포스트에서는 버블 정렬 (Bubble sort)를 다루는 예제코드를 살펴볼 수 있다. 기본적으로 알고 있어야 하고 처음으로 가장 많이 접하는 버블 정렬의 경우 그만큼 사용할 수 있는 방법과 기회가 많다. 따라서 버블 정렬을 어떻게 구현해서 C에서 어떻게 사용하는지를 해당 코드를 통해서 살펴볼 수 있다. 코드에서 산출하고자 하는 내용은 단순하고 많이 봐온 티켓 추첨에 대한 내용이다. 따라서 버블 정렬이 어떻게 코드 내에서 활용되고 있는지를 쉽게 확인할 수 있다. 이러한 주요 functions들의 경우, 다른 프로그래밍 언어에서도 작성 방식만 다르지 동일하게 사용이 되기 때문에 다시 한번 강조해서 확실히 알아두는 것이 좋다. 글쓴이의 경우도 시작을 C++로 했지만 Computer vision과 Blockchain을 거치면서 이제는 웬만한 모든 언어를 사용하고 있다. 익숙지 않은 언어를 보더라도 손쉽게 파악할 수 있는 이유는 바로 코드 내에서 사용하는 기능들은 거의 비슷하기 때문이다.

 

또한 버블 정렬만 가지고 살펴보기에는 다소 심심하기 때문에 티켓 번호로 입력된 값을 두가지 방법으로 비교하여 산출하는 방식을 넣어두었다. 사실 Linear과 Binary search로 나와 있는 Functions들도 버블 정렬에서 정리한 것을 출력하는 것이지만 두 가지를 비교하면서 버블 정렬이 어떻게 다른지 눈으로 확인할 수 있도록 추가해 두었다. 각 주요 기능들과 코드에 대해서 코멘트를 남겨두었으니 참고해서 부분 부분 비교하여 이해하는데 도움이 될 것이다.


#include <stdio.h>

// Function prototypes
void bubbleSort(int arr[], int size);
void swap(int *a, int *b);
int linearSearch(int arr[], int size, int value);
int binarySearch(int arr[], int size, int value);
void printArray(int arr[], int size);

// Main function
int main() {
    int ticket[] = {85647, 62483, 13579, 26792, 52551, 33445, 79422, 76172, 93121, 26791};
    int size = 10;
    int winningNum;
    int choice, result;

    printf("\nEnter your 5-digit lottery number: ");
    scanf("%d", &winningNum);

    printf("Press 1 to perform linear search, 2 for binary search: ");
    scanf("%d", &choice);
    
    printf("\nOriginal values:  ");
    printArray(ticket, size);

    if (choice == 1) {
        result = linearSearch(ticket, size, winningNum);
    } else {
        bubbleSort(ticket, size);
        printf("Sorted   values:    ");
        printArray(ticket, size);
        result = binarySearch(ticket, size, winningNum);
    }

    if (result != -1) {
        printf("You have a winning ticket.\n");
    } else {
        printf("You did not win.\n");
    }

    return 0;
}

// Function to print array elements
void printArray(int arr[], int size) {
    for (int i = 0; i < size; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");
}

// Swap function
void swap(int *a, int *b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}

// Bubble sort function
void bubbleSort(int arr[], int size) {
    for (int maxElement = size - 1; maxElement > 0; maxElement--) {
        for (int index = 0; index < maxElement; index++) {
            if (arr[index] > arr[index + 1]) {
                swap(&arr[index], &arr[index + 1]);
            }
        }
    }
}

// Linear search function
int linearSearch(int arr[], int size, int value) {
    int comparisons = 0;
    for (int i = 0; i < size; i++) {
        comparisons++;
        if (arr[i] == value) {
            printf("\nNumber of comparisons made: %d\n", comparisons);
            return i; // Found the value
        }
    }
    printf("\nNumber of comparisons made: %d\n", comparisons);
    return -1; // Value not found
}

// Binary search function
int binarySearch(int arr[], int size, int value) {
    int first = 0, last = size - 1, middle;
    int comparisons = 0;

    while (first <= last) {
        comparisons++;
        middle = (first + last) / 2;

        if (arr[middle] == value) {
            printf("\nNumber of comparisons made: %d\n", comparisons);
            return middle; // Found the value
        } else if (arr[middle] > value) {
            last = middle - 1;
        } else {
            first = middle + 1;
        }
    }

    printf("\nNumber of comparisons made: %d\n", comparisons);
    return -1; // Value not found
}

Figure 1. Result of example code with linear search


Figure 2. Result of example code with binary search


# github link

[Temp]


 

728x90

댓글