写一个冒泡排序,用5种不同的语言
时间: 2024-02-28 14:57:38 浏览: 55
Ruby语言写一个冒泡排序算法.pdf
好的,以下是五种不同语言实现的冒泡排序代码:
Python 3:
```python
def bubble_sort(arr):
n = len(arr)
for i in range(n):
for j in range(0, n-i-1):
if arr[j] > arr[j+1] :
arr[j], arr[j+1] = arr[j+1], arr[j]
arr = [64, 34, 25, 12, 22, 11, 90]
bubble_sort(arr)
print("Sorted array is:", arr)
```
Java:
```java
public static void bubbleSort(int[] arr) {
int n = arr.length;
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 arr[] = {64, 34, 25, 12, 22, 11, 90};
bubbleSort(arr);
System.out.println("Sorted array is: ");
for (int i=0; i<arr.length; ++i)
System.out.print(arr[i] + " ");
```
C++:
```c++
void bubbleSort(int arr[], int n) {
int i, j;
for (i = 0; i < n-1; i++)
for (j = 0; j < n-i-1; j++)
if (arr[j] > arr[j+1])
swap(arr[j], arr[j+1]);
}
int main() {
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr)/sizeof(arr[0]);
bubbleSort(arr, n);
cout<<"Sorted array is: \n";
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
return 0;
}
```
JavaScript:
```javascript
function bubbleSort(arr) {
var i, j;
for (i = 0; i < arr.length-1; i++)
for (j = 0; j < arr.length-i-1; j++)
if (arr[j] > arr[j+1]) {
var temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
var arr = [64, 34, 25, 12, 22, 11, 90];
bubbleSort(arr);
console.log("Sorted array is: " + arr);
```
PHP:
```php
function bubbleSort(&$arr) {
$n = count($arr);
for($i = 0; $i < $n; $i++) {
for($j = 0; $j < $n - $i - 1; $j++) {
if($arr[$j] > $arr[$j+1]) {
$temp = $arr[$j+1];
$arr[$j+1] = $arr[$j];
$arr[$j] = $temp;
}
}
}
}
$arr = array(64, 34, 25, 12, 22, 11, 90);
bubbleSort($arr);
echo "Sorted array is: ";
for($i = 0; $i < count($arr); $i++) {
echo $arr[$i]." ";
}
```
以上是五种不同语言实现的冒泡排序代码,希望能对您有所帮助。
阅读全文