冒泡排序和选择排序的代码
时间: 2024-02-18 09:57:40 浏览: 66
以下是冒泡排序和选择排序的代码示例:
冒泡排序代码示例(PHP):
```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;
}
// 测试冒泡排序
$testArr = [5, 3, 8, 2, 1];
$sortedArr = bubbleSort($testArr);
echo "冒泡排序结果:";
foreach ($sortedArr as $num) {
echo $num . " ";
}
```
选择排序代码示例(C):
```c
#include <stdio.h>
void selectionSort(int arr[], int n) {
int i, j, minIndex, temp;
for (i = 0; i < n-1; i++) {
minIndex = i;
for (j = i+1; j < n; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
}
int main() {
int arr[10];
int i;
printf("请输入10个数:\n");
for (i = 0; i < 10; i++) {
scanf("%d", &arr[i]);
}
printf("\n");
selectionSort(arr, 10);
printf("由小到大排序:\n");
for (i = 0; i < 10; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
```
阅读全文