插入排序
插入排序升序(自左到右)插入排序降序(自左到右)源代码测试测试结果 插入排序升序(自左到右)
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; }}
源代码测试
//// Created by 15328 on 2022/1/28.//#includeusing 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_CFcmake-build-debugSort_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