c、java、python语言冒泡排序
时间: 2023-09-19 19:10:17 浏览: 74
## C语言实现冒泡排序
```c
#include <stdio.h>
void bubbleSort(int arr[], int n){
int i, j, temp;
for(i = 0; i < n-1; i++){
for(j = 0; j < n-1-i; j++){
if(arr[j] > arr[j+1]){
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
int main(){
int arr[] = {5, 2, 6, 1, 3};
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;
}
```
## Java语言实现冒泡排序
```java
public class BubbleSort {
public static void bubbleSort(int[] arr) {
int n = arr.length;
int temp = 0;
for(int i = 0; i < n-1; i++){
for(int j = 0; j < n-1-i; j++){
if(arr[j] > arr[j+1]){
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
public static void main(String[] args) {
int[] arr = {5, 2, 6, 1, 3};
bubbleSort(arr);
System.out.print("Sorted array: ");
for(int i = 0; i < arr.length; i++){
System.out.print(arr[i] + " ");
}
}
}
```
## Python语言实现冒泡排序
```python
def bubbleSort(arr):
n = len(arr)
for i in range(n-1):
for j in range(n-1-i):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
arr = [5, 2, 6, 1, 3]
bubbleSort(arr)
print("Sorted array:", arr)
```
阅读全文