Bubble sort algorithm (c language article)

Bubble Sort

Bubble sort is also a simple and intuitive sorting algorithm. It repeatedly walks through the sequence to be sorted, comparing two elements at a time and swapping them if they are in the wrong order. The work of visiting the array is repeated until no more exchanges are needed, which means that the array has been sorted. The name of this algorithm comes from the fact that smaller elements will slowly "float" to the top of the array through exchange.

To put it simply, it is:

Start comparing two adjacent elements from the first element. If the first of the two compared elements is larger or smaller than the second, change the position (as for comparing by large or small, it depends on whether you want to go from small to large or Sort from large to small), complete the comparison once, discard the largest or smallest element and continue to compare until the sorting is completed.


Algorithm steps:

  1. Compare adjacent elements. If the first one is bigger than the second one, swap them both.
  2. Do the same for each pair of adjacent elements, starting with the first pair and ending with the last pair. After this step is completed, the final element will be the largest number.
  3. Repeat the above steps for all elements except the last one.
  4. Keep repeating the above steps for fewer and fewer elements each time until there are no pairs of numbers left to compare.

Animation demonstration:

C language code demonstration:

/*
* 冒泡排序算法
*/
#include <stdio.h>
#define SUM 6

//冒泡排序算法函数(数组名作为函数实参时,它会自动被转换为指针,所以可以在bubble_sort函数更换数组的值,而变量不行)
void bubble_sort(int arr[SUM])
{
    int temp, i, j;
    for (i = 0; i <= SUM - 1; i++)
    {
        for (j = 0; j <= SUM - 1 - i; j++)
        {
            if (arr[j] > arr[j + 1])
            {
                temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
            }
        }
    }
}

int main()
{
    int arr[SUM], i;

    //输入数组
    printf("Please enter an array: ");
    for (i = 0; i < SUM; i++)
    {
        scanf("%d", &arr[i]);
    }
    
    bubble_sort(arr);

    //输出数组
    for (i = 0; i < SUM; i++)
    {
        printf("%d ", arr[i]);
    }

    return 0;
}

Here is a question that novices may not understand, that is, the array name can be used as a function parameter to replace the value of the array, but why can't ordinary variables?

Explanation:Because when the array name is used as a function parameter, it will be automatically converted into a pointer, which means that the actual parameter group and the formal parameter group are both in the same memory unit. , if the formal parameter group is modified, the actual parameter group will also be modified, so the value of the array can be replaced in the bubble_sort function, but ordinary variables cannot.

Guess you like

Origin blog.csdn.net/admin_W_KP/article/details/134288730