Home > Computer Tutorials > Computer Knowledge > Sample code for bubble sorting in C language

Sample code for bubble sorting in C language

王林
Release: 2024-01-08 13:46:06
forward
1928 people have browsed it

Bubble Sort is a simple sorting algorithm that repeatedly traverses the array to be sorted, compares two adjacent elements at a time, and swaps them if they are in the wrong order. The following is a sample code using C language to implement bubble sort:

#include <stdio.h>

void bubbleSort(int arr[], int n) {
    for (int i = 0; i < n - 1; i++) {
        // 每轮冒泡将最大的元素移动到末尾
        for (int j = 0; j < n - i - 1; j++) {
            // 如果当前元素比下一个元素大,交换它们的位置
            if (arr[j] > arr[j + 1]) {
                // 交换元素
                int temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
            }
        }
    }
}

int main() {
    int arr[] = {64, 34, 25, 12, 22, 11, 90};
    int n = sizeof(arr) / sizeof(arr[0]);
    
    printf("原始数组:");
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");
    
    // 调用冒泡排序函数
    bubbleSort(arr, n);
    
    printf("排序后的数组:");
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");
    
    return 0;
}
Copy after login

In the above code, the bubbleSort function implements the logic of bubble sort. In the main function, we define an integer array arr, call the bubbleSort function to sort the array, and output the array contents before and after sorting. This example demonstrates how to implement the bubble sort algorithm using C language.

The above is the detailed content of Sample code for bubble sorting in C language. For more information, please follow other related articles on the PHP Chinese website!

source:docexcel.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template