栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

数据结构06:插入排序

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

数据结构06:插入排序

插入排序

插入排序升序(自左到右)插入排序降序(自左到右)源代码测试测试结果

插入排序升序(自左到右)
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.
//
#include
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_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
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/727747.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号