c语言的插入排序代码
时间: 2023-11-12 09:56:46 浏览: 39
好的,以下是 C 语言的插入排序代码:
```c
void insertionSort(int arr[], int n) {
int i, key, j;
for (i = 1; i < n; i++) {
key = arr[i]; j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}
```
相关问题
C语言插入排序代码注释
好的,以下是C语言插入排序的代码和注释:
```
void insertionSort(int arr[], int n) {
int i, key, j;
for (i = 1; i < n; i++) {
key = arr[i]; // 将当前元素存储在key变量中
j = i - 1;
/*
* 将 arr[0] 到 arr[i-1] 排序
* 如果待排序元素小于前一个元素,则将它们交换
*/
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key; // 将 key 插入到已排序的子数组中
}
}
```
该算法的基本思想是:将数组分为已排序和未排序两部分,每次从未排序的部分取出第一个元素,插入到已排序的部分中,以此类推直到数组排序完成。
希望这能解决您的问题。
C语言插入排序完整代码
好的,以下是C语言插入排序的完整代码示例:
```
#include <stdio.h>
void insertionSort(int arr[], int n) {
int i, key, j;
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;
}
}
void printArray(int arr[], int n) {
int i;
for (i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
}
int main() {
int arr[] = { 12, 11, 13, 5, 6 };
int n = sizeof(arr) / sizeof(arr);
insertionSort(arr, n);
printf("Sorted array: \n");
printArray(arr, n);
return 0;
}
```
这是一个简单的插入排序算法,它将一个未排序的数组作为输入,并按照升序(从小到大)的顺序将其排序。函数insertionSort()执行实际的排序操作,而printArray()函数仅用于打印排序后的数组。
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.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)