![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/fd0ba578dd675d2b3396ec0275cc3781.png)
插入排序升序(自左到右)
void insertSort_Asc(elementType* number, int n){
if(n < 2){
return;
}
int i = 0;
for(int j = 1; j < n; j++) {
elementType key = *(number + j);
i = j - 1;
while(i >= 0 && number[i] > key){
*(number + i + 1) = *(number + i);
i--;
}
number[i + 1] = key;
}
}
插入排序降序(自左到右)
void insertSort_Desc(elementType* number, int n){
if(n < 2){
return;
}
int i = 0;
for(int j = 1; j < n; j++) {
elementType key = *(number + j);
i = j - 1;
while(i >= 0 && number[i] < key){
*(number + i + 1) = *(number + i);
i--;
}
number[i + 1] = key;
}
}
源代码测试
#include<bits/stdc++.h>
using namespace std;
typedef double elementType;
void insertSort_Asc(elementType* number, int n){
if(n < 2){
return;
}
int i = 0;
for(int j = 1; j < n; j++) {
elementType key = *(number + j);
i = j - 1;
while(i >= 0 && number[i] > key){
*(number + i + 1) = *(number + i);
i--;
}
number[i + 1] = key;
}
}
void insertSort_Desc(elementType* number, int n){
if(n < 2){
return;
}
int i = 0;
for(int j = 1; j < n; j++) {
elementType key = *(number + j);
i = j - 1;
while(i >= 0 && number[i] < key){
*(number + i + 1) = *(number + i);
i--;
}
number[i + 1] = key;
}
}
void Print(elementType* a,int n){
for(int i = 0; i < n; i++){
cout << *(a+i) << "\t";
}
}
void test(){
int number = 0;
std::cout << "输入待排序序列长度:\n";
cin >> number;
const int num = number;
elementType *a = new elementType [num]();
std::cout << "待排序序列默认初始化为零:\n";
Print(a,num);
printf("\n");
std::cout << "输入该序列元素:\n";
for(int i = 0; i < num; i++){
cin >> a[i];
}
std::cout << "插入排序结果:(升序)\n";
insertSort_Asc(a,num);
Print(a,num);
printf("\n");
std::cout << "插入排序结果:(降序)\n";
insertSort_Desc(a,num);
Print(a,num);
}
int main(){
test();
}
测试结果
E:\CODING__ALAN_CF\cmake-build-debug\Sort_All.exe
输入待排序序列长度:
6
待排序序列默认初始化为零:
0 0 0 0 0 0
输入该序列元素:
66 7.89 6.36 77.89 195779 1627.347
插入排序结果:(升序)
6.36 7.89 66 77.89 1627.35 195779
插入排序结果:(降序)
195779 1627.35 77.89 66 7.89 6.36
进程已结束,退出代码为 0