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); ?>
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; }
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!