已知一组数据{9,3,5,14,7,1,11},分别使用冒泡排序和选择排序方法对数据进行排序,请写出C语言代码
时间: 2024-12-15 07:16:57 浏览: 1
当然可以,下面是使用C语言分别实现冒泡排序和选择排序的例子,针对给定的数据集 `{9, 3, 5, 14, 7, 1, 11}`。
### 冒泡排序 (Bubble Sort)
```c
#include <stdio.h>
void bubbleSort(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;
}
}
}
}
int main() {
int data[] = {9, 3, 5, 14, 7, 1, 11};
int n = sizeof(data) / sizeof(data[0]);
printf("Original array: \n");
for (int i = 0; i < n; i++) {
printf("%d ", data[i]);
}
bubbleSort(data, n);
printf("\nSorted array using Bubble Sort: \n");
for (int i = 0; i < n; i++) {
printf("%d ", data[i]);
}
return 0;
}
```
### 选择排序 (Selection Sort)
```c
#include <stdio.h>
void selectionSort(int arr[], int n) {
for (int i = 0; i < n - 1; i++) {
int min_idx = i;
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[min_idx]) {
min_idx = j;
}
}
// 将找到的最小元素与当前位置的元素交换
int temp = arr[i];
arr[i] = arr[min_idx];
arr[min_idx] = temp;
}
}
int main() {
int data[] = {9, 3, 5, 14, 7, 1, 11};
int n = sizeof(data) / sizeof(data[0]);
printf("Original array: \n");
for (int i = 0; i < n; i++) {
printf("%d ", data[i]);
}
selectionSort(data, n);
printf("\nSorted array using Selection Sort: \n");
for (int i = 0; i < n; i++) {
printf("%d ", data[i]);
}
return 0;
}
```
阅读全文