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

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

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 @   杨谖之  阅读(17)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
点击右上角即可分享
微信分享提示
主题色彩