[GO] Bubble sort

#include <stdio.h>

void SortBubble(int array[], int n, int asc);

int main(void){
    int array[] = {7,1,6,9,3};
    int arraySize = (int)(sizeof(array)/sizeof(array[0]));
    SortBubble(array, arraySize, 1);
    SortBubble(array, arraySize, 0);

    return 0;
}

void SortBubble(int array[], int n, int asc){
    int tmp;

    for(int i = 0; i < n - 1; i++){
        for(int j = 0; j < n - 1; j++){
            if(asc) {
                //ascending order
                if(array[j+1] < array[j]){
                    //j and j+Swap the first value
                    tmp = array[j];
                    array[j] = array[j+1];
                    array[j+1] = tmp;
                }
            } else {
                //descending order
                if(array[j+1] > array[j]){
                    tmp = array[j];
                    array[j] = array[j+1];
                    array[j+1] = tmp;
                }
            }
        }
    }

    asc 
        ? printf("ascending order:")
        : printf("descending order:");
    for(int i = 0; i < n; i++){
        printf("%d,", array[i]);
    } 
    printf("\n");
}

Numerical flow

When i = 0, turning the loop of j ... 1,7,6,9,3 1,6,7,9,3 1,6,7,9,3 1,6,7,3,9

When i = 1, if you turn the loop of j ... 1,6,7,3,9 1,6,7,3,9 1,6,3,7,9 1,6,3,7,9

. . .

output


Ascending order: 1,3,6,7,9,
Descending order: 9,7,6,3,1,

Reference C language bubble sort to remember in pain

Recommended Posts

Bubble sort
Bubble sort without using sort
sort
Bubble sort with fluffy animation
Insertion sort
Selection Sort
[Python] Sort
Python # sort
Implemented bubble sort in Java (BubbleSort)
Implemented Stooge sort in Python3 (Bubble sort & Quicksort)
AOJ Sort I-
Merge Sort Explained
Insertion sort implementation
Hands-on sleep sort
Sort by pandas
Visualize how it is sorted by bubble sort
visualize insertion sort
Python beginners challenge Cpaw CTF Q14 with bubble sort
Bubble sort, selection sort, insertion sort, shell sort, merge sort, quick sort, count sort (Python)