对一维数组进行冒泡法排序
时间: 2023-06-06 08:07:04 浏览: 67
可以,冒泡排序是一种简单的排序算法,通过比较相邻元素的大小来进行排序,时间复杂度为 O(n^2)。对于一维数组,可以通过循环嵌套来实现冒泡排序。具体实现可参考以下伪代码:
for i from 0 to n-1:
for j from 0 to n-i-1:
if arr[j] > arr[j+1]:
swap arr[j] and arr[j+1]
其中,arr表示待排序的一维数组,n表示数组长度。通过不断比较相邻元素的大小并交换位置,最终将数组排序。
相关问题
一维数组排序(冒泡法)c语言
以下是使用冒泡排序法对一维数组进行排序的 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[] = {5, 2, 8, 3, 1, 6};
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;
}
```
输出结果为:
```
Sorted array: 1 2 3 5 6 8
```
该代码先定义了一个 `bubbleSort()` 函数,该函数接受一个整型数组和数组长度作为参数,然后使用冒泡排序法对数组进行排序。然后在 `main()` 函数中创建一个整型数组并初始化,获取数组长度,调用 `bubbleSort()` 函数对数组进行排序,最后输出排序后的数组。
用指针和自定义函数进行一维数组的冒泡排序法
#include <stdio.h>
void bubbleSort(int* arr, int len) {
int i, j, temp;
for (i = 0; i < len - 1; i++) {
for (j = 0; j < len - 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, 3, 8, 4, 2 };
int len = sizeof(arr) / sizeof(int);
int i;
printf("Before sorting: ");
for (i = 0; i < len; i++) {
printf("%d ", *(arr + i));
}
bubbleSort(arr, len);
printf("\nAfter sorting: ");
for (i = 0; i < len; i++) {
printf("%d ", *(arr + i));
}
return 0;
}
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)