c语言使用一维数组元素的指针作为函数参数,编写冒泡法,选择法实现从小到大排序的函数。并编写main()
时间: 2024-02-03 15:14:09 浏览: 96
C语言程序设计-编写函数用冒泡排序法对数组中的数据进行从小到大的排序;.c
5星 · 资源好评率100%
以下是使用指针实现的冒泡排序和选择排序的代码:
```c
#include <stdio.h>
void bubble_sort(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;
}
}
}
}
void selection_sort(int* arr, int n) {
for (int i = 0; i < n - 1; i++) {
int min_index = i;
for (int j = i + 1; j < n; j++) {
if (*(arr + j) < *(arr + min_index)) {
min_index = j;
}
}
int temp = *(arr + i);
*(arr + i) = *(arr + min_index);
*(arr + min_index) = temp;
}
}
int main() {
int arr[] = { 3, 7, 1, 5, 9, 2, 4, 6, 8 };
int n = sizeof(arr) / sizeof(arr[0]);
printf("Original array:\n");
for (int i = 0; i < n; i++) {
printf("%d ", *(arr + i));
}
bubble_sort(arr, n);
printf("\n\nAfter bubble sort:\n");
for (int i = 0; i < n; i++) {
printf("%d ", *(arr + i));
}
selection_sort(arr, n);
printf("\n\nAfter selection sort:\n");
for (int i = 0; i < n; i++) {
printf("%d ", *(arr + i));
}
return 0;
}
```
运行结果如下:
```
Original array:
3 7 1 5 9 2 4 6 8
After bubble sort:
1 2 3 4 5 6 7 8 9
After selection sort:
1 2 3 4 5 6 7 8 9
```
阅读全文