插入排序
#include<iostream>
using namespace std;
void insert_sort(int a[], int n) {
int i, j;
int temp;
for (i = 1; i<n; i++) { //循环从第2个元素开始
if (a[i - 1]>a[i]) {
temp = a[i];
for (j = i - 1; j >= 0 && a[j]>temp; j--) {
a[j + 1] = a[j];
}
a[j + 1] = temp;//此处就是a[j+1]=temp;
}
}
}
void ShellSort(int *arr, int len)
{
int temp = 0;
int count = 0;
for (int gap = len / 2; gap > 0; gap /= 2)
{
for (int i = gap; i < len; i++)
{
int j = i - gap;
while (j >= 0 && arr[j] > arr[j + gap]) //所在分组需做交换
{
temp = arr[j];
arr[j] = arr[j + gap];
arr[j + gap] = temp;
j -= gap;
}
}
}
}
int main() {
int a[8] = { 70,50,30,20,10,70,40,60 };
int n = 8;
cout << "插入排序:";
insert_sort(a, n);
for (int i = 0; i <n; i++) {
cout << a[i] << ' ';
}
cout << endl;
int b[8] = { 70,50,30,20,10,70,40,60 };
cout << "希尔排序:";
ShellSort(b, n);
for (int i = 0; i < n; i++) {
cout << b[i] << ' ';
}
cout << endl;
system("pause");
return 0;
}
https://blog.csdn.net/qq_33289077/article/details/90370899

浙公网安备 33010602011771号