插入排序
C++
直接插入排序
#include <iostream>
#define N 10
using namespace std;
void straightInsertSort(int r[], int n)
{
int i, j, temp;
for (i = 1; i < n; i++)
{
// r[i]插入有序子表, r[0]单个元素也为有序子表
if (r[i] < r[i - 1])
{
temp = r[i]; // r[i]暂存到temp
// 从后向前寻找插入位置,逐个后移,直到找到插入位置
for (j = i - 1; j >= 0 && r[j] > temp; j--)
{
r[j + 1] = r[j];
}
r[j + 1] = temp; //将temp插入r[j + 1]
}
}
}
int main()
{
int numbers[N] = { 3,2,1,5,6,2,8,6,9,7 };
straightInsertSort(numbers, N);
for (int i = 0; i < N; i++)
cout<<numbers[i]<<" ";
cout << "\n";
return 0;
}
希尔排序
#include <iostream>
#define N 10
using namespace std;
void shellSort(int r[], int n)
{
int gap, i, j, temp;
// 按步长进行插入排序
for (gap = n / 2; gap > 0; gap /= 2)
{
for (int i = gap; i < n; i += gap)
{
// r[i]插入有序子表
if (r[i] < r[i - gap])
{
temp = r[i]; // r[i]暂存到temp
// 从后向前寻找插入位置,逐个后移,直到找到插入位置
for (j = i - gap; j >= 0 && r[j] > temp; j -= gap)
{
r[j + gap] = r[j];
}
r[j + gap] = temp; //将temp插入r[j + 1]
}
}
}
}
int main()
{
int numbers[N] = { 3,2,1,5,6,2,8,6,9,7 };
shellSort(numbers, N);
for (int i = 0; i < N; i++)
cout << numbers[i] << " ";
cout << "\n";
return 0;
}
python
直接插入排序
def straight_insert_sort(data):
for i in range(1, len(data)):
j = i
while j >= 1 and data[j-1] > data[j]:
data[j - 1], data[j] = data[j], data[j - 1]
j -= 1
if __name__ == '__main__':
data = [3, 2, 1, 5, 6, 2, 8, 6, 9, 7]
straight_insert_sort(data)
print(data)
希尔排序
def shell_sort(data):
n = len(data)
# 初始步长
gap = n // 2
while gap > 0:
# 按步长进行插入排序
for i in range(gap, n):
j = i
# 插入排序
while j >= gap and data[j - gap] > data[j]:
data[j - gap], data[j] = data[j], data[j - gap]
j -= gap
# 得到新的步长
gap = gap // 2
if __name__ == '__main__':
data = [3, 2, 1, 5, 6, 2, 8, 6, 9, 7]
shell_sort(data)
print(data)