最坏情况下,直接插入排序时间复杂度为θ(n²),最小时间代价为θ(n),平均时间代价为θ(n²)
需要一个辅助存储单位
紧密性,有一个比较,三个赋值操作(越紧密,算法的时间复杂度系数越小)
具有原址性(在任何时候,最多只有其中常数个数字存储在数组外面。)
具有稳定性(假定在待排序的记录序列中,存在多个具有相同的关键字的记录,若经过排序,这些记录的相对次序保持不变;排序算法是否为稳定的是由具体算法决定的,不稳定的算法在某种条件下可以变为稳定的算法,而稳定的算法在某种条件下也可以变为不稳定的算法)
算法类型:插入排序
函数调用的时间代价要远远大于内嵌代码段的时间代价
C++
需要一个辅助存储单位
紧密性,有一个比较,三个赋值操作(越紧密,算法的时间复杂度系数越小)
具有原址性(在任何时候,最多只有其中常数个数字存储在数组外面。)
具有稳定性(假定在待排序的记录序列中,存在多个具有相同的关键字的记录,若经过排序,这些记录的相对次序保持不变;排序算法是否为稳定的是由具体算法决定的,不稳定的算法在某种条件下可以变为稳定的算法,而稳定的算法在某种条件下也可以变为不稳定的算法)
算法类型:插入排序
函数调用的时间代价要远远大于内嵌代码段的时间代价
C++
- #include <iostream>
- using namespace std;
- /*交换函数,作用是交换数组中的两个元素的位置*/
- void swap(int array[],int i,int j)
- {
- int tmp=array[i];
- array[i]=array[j];
- array[j]=tmp;
- }
- /*插入排序*/
- void InsertSort(int array[],int n)
- {
- for(int i=1;i<n;i++)
- {
- for(int j=i;j>0;j--)
- {
- if(array[j]>array[j-1])
- swap(array,j,j-1); //形参array是数组名
- else
- break;
- }
- }
- }
- int main()
- {
- int array[5]={3,1,2,5,4};
- InsertSort(array,5);
- for(int i=0;i<5;i++)
- cout<<array[i]<<" ";
- cout<<endl;
- return 0;
- }
c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
//数组的记录类型
struct RecType
{
public int key;
public string data;
}
//排序类
class InterSortClass
{
const int MaxSize = 100;
public RecType[] R;
public int length;
public InterSortClass()
{
R = new RecType[MaxSize];
length =0;
}
//插入排序
public void InsertSort()
{
for (int i = 1; i < length; i++)
{
for (int j = i; j > 0; j--)
{
if (R[j - 1].key < R[j].key)
{
Swap(ref R[j - 1],ref R[j]); //数据交换
}
else
break;
}
}
}
//数据交换
public void Swap(ref RecType a, ref RecType b)
{
RecType tmp = a;
a = b;
b = tmp;
}
//数组初始化
public void CreateList()
{
string a = Console.ReadLine();
string[] b = a.Split(new char[] { ',' });
for (int i = 0; i < b.Length; i++)
{
R[i].key = Convert.ToInt32(b[i]);
}
length = b.Length;
}
}
}
static void Main(string[] args)
{
InterSortClass L = new InterSortClass();
L.CreateList();
L.InsertSort();
for (int i = 0; i < L.length-1; i++)
{
Console.Write(L.R[i].key);
Console.Write(",");
}
Console.WriteLine(L.R[L.length-1].key);
Console.ReadKey();
}