Home > Computer Tutorials > Computer Knowledge > Example of bubble sort written in PHP and C language

Example of bubble sort written in PHP and C language

PHPz
Release: 2024-01-08 20:27:01
forward
1050 people have browsed it

PHP bubble sort example:

In PHP, bubble sort can be implemented through nested loops, comparing adjacent elements and swapping the order until the entire array is sorted.

<?php
function bubbleSort($arr) {
    $n = count($arr);
    for ($i = 0; $i < $n - 1; $i++) {
        for ($j = 0; $j < $n - $i - 1; $j++) {
            if ($arr[$j] > $arr[$j + 1]) {
                // 交换元素
                $temp = $arr[$j];
                $arr[$j] = $arr[$j + 1];
                $arr[$j + 1] = $temp;
            }
        }
    }
    return $arr;
}

// 示例用法
$unsortedArray = [64, 34, 25, 12, 22, 11, 90];
$sortedArray = bubbleSort($unsortedArray);
echo "Sorted array: " . implode(", ", $sortedArray);
?>
Copy after login

C Bubble sorting example:

In C language, bubble sorting is also implemented through nested loops, comparing adjacent elements and exchanging order, until until the entire array is sorted.

#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]);
    bubbleSort(arr, n);
    printf("Sorted array: ");
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    return 0;
}
Copy after login

Summary:

Bubble sorting is a simple sorting algorithm that achieves sorting by comparing and exchanging adjacent elements. Whether in PHP or C language, its basic idea and implementation are the same. In PHP, array operations are more convenient, while in C language, you need to manually manage arrays and output results. Regardless of the language, understanding and implementing bubble sort can help you understand the basic principles of sorting algorithms.

The above is the detailed content of Example of bubble sort written in PHP and 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