用c语言写一个冒泡排序
时间: 2023-09-20 08:05:47 浏览: 49
### 回答1:
当然可以!以下是使用C语言实现冒泡排序:
```
#include <stdio.h>
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]) {
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
int main() {
int arr[] = {5, 2, 8, 4, 0, 1, 9, 6, 3, 7};
int n = sizeof(arr)/sizeof(arr[0]);
printf("Original array: ");
for(int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
bubbleSort(arr, n);
printf("\nSorted array: ");
for(int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
return 0;
}
```
在这个示例代码中,我们使用了两个嵌套的循环来遍历数组并比较相邻的元素。如果当前一个元素大于下一个元素,我们就交换它们。这个过程直到整个数组完全排序。输出原始数组和排序后的数组。
### 回答2:
冒泡排序是一种简单的排序算法,它通过不断比较相邻的两个元素并交换位置来将较大的元素逐步“冒泡”到数组末尾。以下是用 C 语言实现冒泡排序的代码:
```c
#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[] = {5, 2, 8, 4, 1};
int n = sizeof(arr) / sizeof(arr[0]);
bubbleSort(arr, n);
printf("排序后的数组:");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
return 0;
}
```
以上代码中,`bubbleSort` 函数接收一个整数数组 `arr` 和数组长度 `n`。通过两层嵌套循环,比较相邻的两个元素并交换位置,最终实现从小到大的排序。在 `main` 函数中,我们定义了一个待排序的整数数组 `arr`,并计算出数组长度 `n`,然后调用 `bubbleSort` 函数对数组进行排序。最后,使用循环打印排序后的数组元素。
运行以上代码,输出结果为:`排序后的数组:1 2 4 5 8`。说明冒泡排序成功将数组按照从小到大的顺序进行了排序。
### 回答3:
冒泡排序是一种简单而基本的排序算法。其基本思想是从待排序的第一个元素开始,比较相邻的元素,如果顺序不正确就交换它们,重复这个过程,直到整个序列都被排序。
以下是用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-i-1; j++) {
if (arr[j] > arr[j+1]) {
// 交换两个元素
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]);
printf("未排序数组:\n");
for (int i=0; i < n; i++) {
printf("%d ", arr[i]);
}
bubbleSort(arr, n);
printf("\n排序后数组:\n");
for (int i=0; i < n; i++) {
printf("%d ", arr[i]);
}
return 0;
}
```
以上代码定义了一个`bubbleSort`函数来执行冒泡排序。在`main`函数中,我们定义了一个待排序的数组`arr`,并使用`sizeof`操作符和数组元素的大小来计算数组的长度`n`。然后我们调用`bubbleSort`函数来对数组进行排序,并在排序前后输出数组的内容。
运行上述代码将得到以下输出:
```
未排序数组:
64 34 25 12 22 11 90
排序后数组:
11 12 22 25 34 64 90
```
我们可以看到,使用冒泡排序算法能够将数组按照升序进行排序。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![text/plain](https://img-home.csdnimg.cn/images/20210720083646.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![c](https://img-home.csdnimg.cn/images/20210720083646.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)