c语言指针冒泡排序代码
时间: 2023-10-13 15:20:11 浏览: 57
以下是C语言指针冒泡排序代码:
```
void bubble_sort(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;
}
}
}
}
```
请注意,本AI并不是真正的编程语言解释器,我只是一个AI模型。我无法编译代码或运行程序。
相关问题
c语言指针实现的冒泡排序代码
好的,C语言中使用指针实现冒泡排序的代码如下:
```
#include <stdio.h>
void bubble_sort(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 i, n, arr[100];
printf("Enter number of elements: ");
scanf("%d", &n);
printf("Enter %d elements:\n", n);
for (i = 0; i < n; i++) {
scanf("%d", arr+i);
}
bubble_sort(arr, n);
printf("Sorted array in ascending order:\n");
for (i = 0; i < n; i++) {
printf("%d ", *(arr+i));
}
printf("\n");
return 0;
}
```
函数`bubble_sort`的参数中,`int *arr`表示指向整型数组的指针,`int n`表示数组的元素个数。在函数中使用指针的方式来访问数组元素,通过指针的移动来交换元素位置。
在主函数中,先输入数组元素并调用`bubble_sort`函数进行排序,最后输出排序后的结果。
c语言指针实现冒泡排序
下面是用指针实现冒泡排序的C语言代码:
```c
#include <stdio.h>
void bubble_sort(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[] = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5};
int n = sizeof(arr) / sizeof(int);
int i;
printf("Before sorting: ");
for (i = 0; i < n; i++) {
printf("%d ", *(arr+i));
}
printf("\n");
bubble_sort(arr, n);
printf("After sorting: ");
for (i = 0; i < n; i++) {
printf("%d ", *(arr+i));
}
printf("\n");
return 0;
}
```
在这个代码中,我们使用指针访问数组元素。在函数 bubble_sort 中,我们用指针访问数组元素,而不是使用下标。需要注意的是,指针加法和指针减法的优先级高于解引用操作,所以我们需要用圆括号括起来。
在主函数中,我们使用指针访问数组元素,并将它们传递给 bubble_sort 函数。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)