插入排序算法算法设计
时间: 2023-11-16 08:01:44 浏览: 64
插入排序算法的基本思想是每次将一个待排序的元素,按其大小插入到已经排好序的子序列的适当位置,直到全部元素插入完成为止。具体实现时,插入排序会将序列分为两部分:头部是已经排序完毕的,尾部是待排序的状态。从头开始扫描每一个元素,每当扫描一个元素,就将它插入到头部合适的位置,使得头部数据依然保持有序。插入排序算法的时间复杂度为O(n^2),空间复杂度为O(1)。
以下是Java实现插入排序算法的代码:
```java
public class InsertionSort<T extends Comparable<T>> extends Sort<T> {
@Override
protected void sort() {
for (int begin = 1; begin < arr.length; begin++) {
int cur = begin;
while (cur > 0 && cmp(cur, cur - 1) < 0) {
swap(cur, cur - 1);
cur--;
}
}
}
}
```
相关问题
直接插入排序算法算法设计描述
直接插入排序算法是一种简单的排序算法,其基本思想是将待排序的元素插入到已经排好序的序列中,从而得到一个新的、更大的有序序列。具体的算法设计描述如下:
1. 将待排序的序列分为两个部分:已排序区和未排序区。
2. 初始时,已排序区只包含一个元素,即序列的第一个元素。
3. 依次将未排序区的元素插入到已排序区中,直到未排序区为空。
4. 对于未排序区中的每个元素,从后往前扫描已排序区,找到插入位置并插入。
下面是一个Python实现的直接插入排序算法的例子:
```python
def insertion_sort(arr):
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
while j >= 0 and arr[j] > key:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
return arr
```
链式存储结构设计直接插入排序算法
链式存储结构设计直接插入排序算法的步骤如下:
1. 定义一个链表节点类,包含一个值和一个指向下一个节点的指针。
2. 创建一个空链表,并将第一个节点的值设置为待排序序列的第一个元素。
3. 遍历待排序序列的剩余元素,对每个元素执行以下操作:
- 创建一个新的节点,并将其值设置为当前待排序元素的值。
- 从链表的头节点开始,依次比较节点的值和新节点的值,直到找到一个节点的值大于新节点的值或者到达链表的末尾。
- 将新节点插入到找到的节点之前,或者作为链表的最后一个节点。
4. 遍历完所有待排序元素后,链表中的节点就是按照从小到大的顺序排列的。
下面是一个示例代码:
```python
class Node:
def __init__(self, value):
self.value = value
self.next = None
def insert_sort(head, value):
new_node = Node(value)
if head is None:
return new_node
if value < head.value:
new_node.next = head
return new_node
curr = head
while curr.next is not None and curr.next.value < value:
curr = curr.next
new_node.next = curr.next
curr.next = new_node
return head
def print_list(head):
curr = head
while curr is not None:
print(curr.value, end=" ")
curr = curr.next
print()
# 示例使用
values = [5, 2, 8, 3, 1]
head = None
for value in values:
head = insert_sort(head, value)
print_list(head)
```
输出结果为:1 2 3 5 8
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.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)