用C语言在一个程序中实现数据结构的多种排序方法,要求能够输入数据
时间: 2024-02-05 20:14:19 浏览: 93
实现多种排序方法的程序可以使用 C 语言来编写。以下是一个示例程序,它可以实现冒泡排序、选择排序和插入排序。程序可以从用户输入中读取数据,并将排序后的结果输出到屏幕上。
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100
void bubble_sort(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 selection_sort(int arr[], int size) {
int i, j, min;
for (i = 0; i < size - 1; i++) {
min = i;
for (j = i + 1; j < size; j++) {
if (arr[j] < arr[min]) {
min = j;
}
}
int temp = arr[i];
arr[i] = arr[min];
arr[min] = temp;
}
}
void insertion_sort(int arr[], int size) {
int i, j, key;
for (i = 1; i < size; i++) {
key = arr[i];
j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}
}
int main() {
int arr[MAX_SIZE];
int size, i;
printf("Enter the size of array: ");
scanf("%d", &size);
printf("Enter the elements of array: ");
for (i = 0; i < size; i++) {
scanf("%d", &arr[i]);
}
bubble_sort(arr, size);
printf("Bubble Sort: ");
for (i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
selection_sort(arr, size);
printf("Selection Sort: ");
for (i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
insertion_sort(arr, size);
printf("Insertion Sort: ");
for (i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
```
在上面的程序中,我们定义了三个排序函数:冒泡排序、选择排序和插入排序。每个函数都接受一个整数数组和数组大小作为参数,并在函数内部对数组进行排序。在主函数中,我们从用户输入中读取数组大小和元素,并传递给排序函数进行排序。最后,我们将排序后的结果输出到屏幕上。
阅读全文
相关推荐
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)