用一段C语言实现简单选择排序、直接插入排序和冒泡排序。
时间: 2024-03-03 10:51:33 浏览: 59
好的,以下是三种排序算法的C语言实现:
1. 简单选择排序:
```c
void selection_sort(int arr[], int n) {
int i, j, min_idx;
for (i = 0; i < n-1; i++) {
min_idx = i;
for (j = i+1; j < n; j++) {
if (arr[j] < arr[min_idx]) {
min_idx = j;
}
}
// Swap the found minimum element with the first element
int temp = arr[min_idx];
arr[min_idx] = arr[i];
arr[i] = temp;
}
}
```
2. 直接插入排序:
```c
void insertion_sort(int arr[], int n) {
int i, j, key;
for (i = 1; i < n; i++) {
key = arr[i];
j = i - 1;
// Move elements of arr[0..i-1], that are greater than key, to one position ahead of their current position
while (j >= 0 && arr[j] > key) {
arr[j+1] = arr[j];
j = j - 1;
}
arr[j+1] = key;
}
}
```
3. 冒泡排序:
```c
void bubble_sort(int arr[], int n) {
int i, j;
for (i = 0; i < n-1; i++) {
// Last i elements are already in place
for (j = 0; j < n-i-1; j++) {
if (arr[j] > arr[j+1]) {
// Swap arr[j] and arr[j+1]
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
```
这些算法都是经典的排序算法,可以用于对数组进行排序。
阅读全文