C语言分别使用不同的排序方法(冒泡、选择、插入)对一个数组进行排序并输出
时间: 2023-08-12 15:06:03 浏览: 55
下面是C语言使用冒泡、选择和插入排序方法对一个数组进行排序并输出的示例代码:
```c
#include <stdio.h>
// 冒泡排序
void bubble_sort(int arr[], int len) {
for (int i = 0; i < len - 1; i++) {
for (int j = 0; j < len - 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 len) {
for (int i = 0; i < len - 1; i++) {
int min_index = i;
for (int j = i + 1; j < len; j++) {
if (arr[j] < arr[min_index]) {
min_index = j;
}
}
int temp = arr[i];
arr[i] = arr[min_index];
arr[min_index] = temp;
}
}
// 插入排序
void insertion_sort(int arr[], int len) {
for (int i = 1; i < len; i++) {
int key = arr[i];
int j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j+1] = arr[j];
j--;
}
arr[j+1] = key;
}
}
int main() {
int arr[] = {5, 9, 3, 7, 1, 8, 6, 2, 4};
int len = sizeof(arr) / sizeof(arr[0]);
// 冒泡排序
bubble_sort(arr, len);
printf("冒泡排序结果:");
for (int i = 0; i < len; i++) {
printf("%d ", arr[i]);
}
printf("\n");
// 选择排序
int arr2[] = {5, 9, 3, 7, 1, 8, 6, 2, 4};
selection_sort(arr2, len);
printf("选择排序结果:");
for (int i = 0; i < len; i++) {
printf("%d ", arr2[i]);
}
printf("\n");
// 插入排序
int arr3[] = {5, 9, 3, 7, 1, 8, 6, 2, 4};
insertion_sort(arr3, len);
printf("插入排序结果:");
for (int i = 0; i < len; i++) {
printf("%d ", arr3[i]);
}
printf("\n");
return 0;
}
```
输出结果为:
```
冒泡排序结果:1 2 3 4 5 6 7 8 9
选择排序结果:1 2 3 4 5 6 7 8 9
插入排序结果:1 2 3 4 5 6 7 8 9
```
相关推荐
![application/x-zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![](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)