插入排序改写递归算法
时间: 2024-03-24 08:34:49 浏览: 27
插入排序是一种简单直观的排序算法,它的基本思想是将一个待排序的元素插入到已经排好序的部分中,从而得到一个新的有序序列。下面是插入排序的递归算法改写:
```python
def insertion_sort(arr):
if len(arr) <= 1:
return arr
# 递归地对前n-1个元素进行排序
sorted_arr = insertion_sort(arr[:-1])
# 将最后一个元素插入到已排序的部分中
last_element = arr[-1]
i = len(sorted_arr) - 1
while i >= 0 and sorted_arr[i] > last_element:
sorted_arr[i+1] = sorted_arr[i]
i -= 1
sorted_arr[i+1] = last_element
return sorted_arr
```
这个递归算法的思路是先对前n-1个元素进行排序,然后将第n个元素插入到已排序的部分中。通过递归调用,不断缩小问题规模,直到只剩下一个元素时,递归终止。
相关问题
直接插入排序的递归算法
直接插入排序是一种简单的排序算法,它的递归算法实现如下:
1. 基本情况:如果数组长度为1或者为空,则无需排序,直接返回。
2. 递归步骤:
a. 对除最后一个元素外的子数组进行递归排序。
b. 将最后一个元素插入已排序的子数组中的正确位置。
下面是直接插入排序的递归算法示例代码:
```python
def insertion_sort_recursive(arr):
# 基本情况
if len(arr) <= 1:
return arr
# 递归步骤
sorted_arr = insertion_sort_recursive(arr[:-1]) # 对除最后一个元素外的子数组进行递归排序
last_element = arr[-1] # 最后一个元素
# 将最后一个元素插入已排序的子数组中的正确位置
i = len(sorted_arr) - 1
while i >= 0 and sorted_arr[i] > last_element:
sorted_arr[i+1] = sorted_arr[i]
i -= 1
sorted_arr[i+1] = last_element
return sorted_arr
```
C语言直接插入排序的递归算法
C语言直接插入排序的递归算法是一种基于插入排序的排序算法,它通过递归的方式将待排序的数组分为已排序和未排序两部分,然后将未排序部分的元素依次插入到已排序部分的正确位置上。
以下是C语言直接插入排序的递归算法的实现步骤:
1. 首先定义一个递归函数,命名为`insertionSortRecursive`,该函数接受一个整型数组和数组长度作为参数。
2. 在`insertionSortRecursive`函数中,首先判断数组长度是否小于等于1,如果是,则直接返回。
3. 如果数组长度大于1,则递归调用`insertionSortRecursive`函数,传入除第一个元素外的子数组,并将子数组排序。
4. 在递归调用返回后,将第一个元素插入到已排序的子数组中的正确位置上。
5. 最后,完成递归调用后,整个数组就会被排序。
下面是C语言直接插入排序的递归算法的示例代码:
```c
void insertionSortRecursive(int arr[], int n) {
// Base case
if (n <= 1)
return;
// Sort first n-1 elements
insertionSortRecursive(arr, n-1);
// Insert last element at its correct position in sorted array
int last = arr[n-1];
int j = n-2;
while (j >= 0 && arr[j] > last) {
arr[j+1] = arr[j];
j--;
}
arr[j+1] = last;
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)