编写程序C语言分别用冒泡法和选择法并且分别用指针和普通函数给12个整数排序
时间: 2023-12-03 16:46:04 浏览: 69
C语言程序设计-编写函数用冒泡排序法对数组中的数据进行从小到大的排序;.c
5星 · 资源好评率100%
使用指针实现冒泡排序:
```c
#include <stdio.h>
void bubble_sort(int *arr, int n) {
int i, j, temp;
for (i = 0; i < n - 1; i++) {
for (j = i + 1; j < n; j++) {
if (*(arr + j) < *(arr + i)) {
temp = *(arr + i);
*(arr + i) = *(arr + j);
*(arr + j) = temp;
}
}
}
}
int main() {
int arr[] = {12, 7, 9, 14, 5, 23, 18, 3, 27, 16, 11, 21};
int n = sizeof(arr) / sizeof(arr[0]);
int i;
printf("Original array:");
for (i = 0; i < n; i++) {
printf(" %d", *(arr + i));
}
bubble_sort(arr, n);
printf("\nSorted array:");
for (i = 0; i < n; i++) {
printf(" %d", *(arr + i));
}
return 0;
}
```
使用指针实现选择排序:
```c
#include <stdio.h>
void selection_sort(int *arr, int n) {
int i, j, min_index, temp;
for (i = 0; i < n - 1; i++) {
min_index = i;
for (j = i + 1; j < n; j++) {
if (*(arr + j) < *(arr + min_index)) {
min_index = j;
}
}
temp = *(arr + i);
*(arr + i) = *(arr + min_index);
*(arr + min_index) = temp;
}
}
int main() {
int arr[] = {12, 7, 9, 14, 5, 23, 18, 3, 27, 16, 11, 21};
int n = sizeof(arr) / sizeof(arr[0]);
int i;
printf("Original array:");
for (i = 0; i < n; i++) {
printf(" %d", *(arr + i));
}
selection_sort(arr, n);
printf("\nSorted array:");
for (i = 0; i < n; i++) {
printf(" %d", *(arr + i));
}
return 0;
}
```
使用普通函数实现冒泡排序:
```c
#include <stdio.h>
void bubble_sort(int arr[], int n) {
int i, j, temp;
for (i = 0; i < n - 1; i++) {
for (j = i + 1; j < n; j++) {
if (arr[j] < arr[i]) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
}
int main() {
int arr[] = {12, 7, 9, 14, 5, 23, 18, 3, 27, 16, 11, 21};
int n = sizeof(arr) / sizeof(arr[0]);
int i;
printf("Original array:");
for (i = 0; i < n; i++) {
printf(" %d", arr[i]);
}
bubble_sort(arr, n);
printf("\nSorted array:");
for (i = 0; i < n; i++) {
printf(" %d", arr[i]);
}
return 0;
}
```
使用普通函数实现选择排序:
```c
#include <stdio.h>
void selection_sort(int arr[], int n) {
int i, j, min_index, temp;
for (i = 0; i < n - 1; i++) {
min_index = i;
for (j = i + 1; j < n; j++) {
if (arr[j] < arr[min_index]) {
min_index = j;
}
}
temp = arr[i];
arr[i] = arr[min_index];
arr[min_index] = temp;
}
}
int main() {
int arr[] = {12, 7, 9, 14, 5, 23, 18, 3, 27, 16, 11, 21};
int n = sizeof(arr) / sizeof(arr[0]);
int i;
printf("Original array:");
for (i = 0; i < n; i++) {
printf(" %d", arr[i]);
}
selection_sort(arr, n);
printf("\nSorted array:");
for (i = 0; i < n; i++) {
printf(" %d", arr[i]);
}
return 0;
}
```
阅读全文