Loading

【基础算法】简单排序-冒泡排序

【基础算法】简单排序-冒泡排序

Bubble Sort is the simplest sorting algorithm that works by repeatly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity is quite high.

How does Bubble Sort Work?

Input: arr[]={5,1,4,2,8}

First Pass:

  • Bubble sort starts with very first two elements, comparing them to check which one is greater.
    • ( 5 1 4 2 8 ) -> ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps since 5 > 1.
    • ( 1 5 4 2 8 ) -> ( 1 4 5 2 8 ), Swap since 5 > 4.
    • ( 1 4 5 2 8 ) -> ( 1 4 2 5 8 ), Swap since 5 > 2.
    • ( 1 4 2 5 8 ) -> ( 1 4 2 5 8 ), Now, since these elements are already in order ( 8 > 5 ), algorithm does not swap them.

Second Pass:

  • Now, during second iteration it should look like this:
    • ( 1 4 2 5 8 ) –> ( 1 4 2 5 8 )
    • ( 1 4 2 5 8 ) –> ( 1 2 4 5 8 ), Swap since 4 > 2
    • ( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
    • ( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )

Third Pass:

  • Now, the array is already sorted, but our algorithm does not know if it is completed.
  • The algorithm needs one whole pass without any swap to know it is sorted.
    • ( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
    • ( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
    • ( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
    • ( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )

Code:

#include <stdio.h>
#include <malloc.h>

int main() {
    setbuf(stdout, 0);
    int n = 0;
    printf("请输入数组长度:");
    scanf("%d", &n);
    int* nums = malloc(sizeof(int) * n);
    for(int i=0; i<n; i++) {
        scanf("%d", nums+i);
    }
    // Sorting
    int temp = 0;
    for(int i=0; i<n-1; i++) {
        for (int j=0; j<n-1-i; j++) {
            if (*(nums+j) > *(nums+j+1)) {
                temp = *(nums+j);
                *(nums+j) = *(nums+j+1);
                *(nums+j+1) = temp;
            }
        }
    }
    for(int i=0; i<n; i++) {
        printf("%d ", *(nums+i));
    }
    return 0;
}
posted @ 2023-03-18 17:00  杨谖之  阅读(13)  评论(0编辑  收藏  举报