使用指向一维数组元素的指针作为函数参数,编写冒泡法、选择法实现从小到大排序的函数。并编写main(函数实现排序。
时间: 2024-05-07 11:21:52 浏览: 81
以下是使用指针实现冒泡排序和选择排序的代码:
```c
#include <stdio.h>
void bubbleSort(int *arr, int size) {
int i, j;
for (i = 0; i < size - 1; i++) {
for (j = 0; j < size - i - 1; j++) {
if (*(arr + j) > *(arr + j + 1)) {
int temp = *(arr + j);
*(arr + j) = *(arr + j + 1);
*(arr + j + 1) = temp;
}
}
}
}
void selectionSort(int *arr, int size) {
int i, j, minIndex;
for (i = 0; i < size - 1; i++) {
minIndex = i;
for (j = i + 1; j < size; j++) {
if (*(arr + j) < *(arr + minIndex)) {
minIndex = j;
}
}
if (minIndex != i) {
int temp = *(arr + i);
*(arr + i) = *(arr + minIndex);
*(arr + minIndex) = temp;
}
}
}
int main() {
int arr[] = {3, 8, 2, 5, 1, 4, 7, 6};
int size = sizeof(arr) / sizeof(arr[0]);
// bubble sort
bubbleSort(arr, size);
printf("Bubble sort result: ");
for (int i = 0; i < size; i++) {
printf("%d ", *(arr + i));
}
printf("\n");
// selection sort
selectionSort(arr, size);
printf("Selection sort result: ");
for (int i = 0; i < size; i++) {
printf("%d ", *(arr + i));
}
printf("\n");
return 0;
}
```
运行结果:
```
Bubble sort result: 1 2 3 4 5 6 7 8
Selection sort result: 1 2 3 4 5 6 7 8
```
阅读全文