博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
插入排序
阅读量:4676 次
发布时间:2019-06-09

本文共 1945 字,大约阅读时间需要 6 分钟。

插入排序的步骤如下:

 1. 设定待排列数组的第一位为已知有序序列,指针指向第一位。

 2. 若数组长度大于1,则指针从指向第二位开始,将指针向后移动一位,每次移动之前,将指针所指位置与指针所指位置之前的有序数列进行比对,经过若干次交换后获得新的有序数列。重复本步骤直至整个数组为有序数列。

代码如下:

头文件Sort.h

//自己编写的各种排序算法的头文件。//使用静态类型的函数是为了在调用时候不需要实例化,直接通过类名调用。#ifndef _SORT_H#define _SORT_H//冒泡排序class bubble_sort{private:    int *Array,Length;public:    bubble_sort(int *Array1,int Length);    int *sort_bubble();};//归并排序class merge_sort{public:     static void sort_merge(int Array1[], int Array2[], int Left, int Rightend, int Right,int recursion/*递归flag*/);     static void Merge(int Array1[], int Array2[], int Left, int Rightend);//递归方法     static void Merge_pass(int Array1[], int Array2[], int ordered_len,int Length);     static void Merge1(int Array1[], int Array2[], int Length);//非递归方法};class quick_sort{public:    static void sort_quick(int Array1[],int Left,int right);    };//插入排序class insertion_sort{public:    static void sort_insertion(int Array[],int n);};#endif

insertion_sort.cpp

#include "Sort.h"void insertion_sort::sort_insertion(int Array[],int n){    if (n > 1)    {        for (int i = 1; i < n; i++)        {            int point = i;            for (int j = point - 1; j >= 0; j--,point--)            {                if (Array[j] <= Array[point])                    break;                else                {                    int temp = Array[j];                    Array[j] = Array[point];                    Array[point] = temp;                }            }        }    }}

main.cpp

#include 
#include "Sort.h"using namespace std;void main(){ int Array[] = { 3, 2, 5, 7, 6, 2, 8, 10, 22, 434, 66 }; int Array1[] = { 1 }; int Array2[] = { 5, 4, 3, 2, 1 }; int n = sizeof(Array2) / sizeof(int); insertion_sort::sort_insertion(Array2, n); for (int i = 0; i < n;i++) cout << Array2[i] << endl; system("pause");}

总结一下:

    插入排序的时间复杂度是O(n^2)。是比较简单的一种排序,作者也是现学现用,若有不足之处欢迎指出。

转载于:https://www.cnblogs.com/leo-lv/p/10893531.html

你可能感兴趣的文章
Java 面向对象 之 final 关键字
查看>>
Contact Form 7邮件发送失败的解决办法
查看>>
P1800 software_NOI导刊2010提高(06)
查看>>
Python学习日记(1)使用if __name__ == "main"
查看>>
二进制的最大公约数
查看>>
Mybatis学习笔记(一) 之框架原理
查看>>
ABSTRACT的方法是否可同时是STATIC,是否可同时是NATIVE,是否可同时是SYNCHRONIZED?
查看>>
【SPL标准库专题(10)】SPL Exceptions
查看>>
《Python从入门基础到实践》
查看>>
【读入优化】
查看>>
python-网络编程urllib模块
查看>>
0029 Java学习笔记-面向对象-枚举类
查看>>
CGRectGet *** 获取控件坐标的方法
查看>>
SQL的主键和外键约束
查看>>
Bookmarklet
查看>>
c++primer 第l六章编程练习答案
查看>>
上海秋季HCC小记
查看>>
Illustrator 上色
查看>>
truncate表恢复
查看>>
this关键字的使用
查看>>