折半查找插入排序算法

时间复杂度 :θ(n²)  

附加存储空间:一个存储单元

稳定性:稳定

原址性:是

特点:是对直接插入排序算法的一种改进,通过折半查找,减少了比较次数,移动次数没变。

与直接插入排序的比较:当数据量越大,原始的排序越凌乱,特别是排序前后单个元素次序变化巨大时,折半插入排序快;否则,直接插入排序快

#include <iostream>
using namespace std;

struct RecType
{
	int key;
	string data;
};

void BinInsertSort(RecType *p,int length)
{
	for (int i =2;i <length;i ++)
	{
		p[0]=p [i ];             //暂存
		int low=1;
		int high=i -1;
		while (low <=high)          //折半查找
		{
			int mid=(low+high)/2;
			if (p[0].key<p[mid].key)
			{
				high=mid-1;
			}
			else                   //关键字相同时,插入到高半区,保证算法的稳定性
			{
				low=mid+1;
			}
		}
		for (int j=i -1;j >=high+1;j --)   //移动记录
		{
			p [j +1]=p [j ];
		}
		p[high+1]=p[0];           //插入
	}
}

int main()
{
	int b;
	RecType R[8];
	for (int i=1;i <8;i ++)
	{
		cin>>R [i ].key;
	}
	BinInsertSort(R ,8);
	for (int i=1;i <8;i ++)
	{
		cout<<R [i ].key<<endl;
	}
	cin>>b;
	return 0;
}

C#

public struct RecType  //数据节点类型
    {
        public int Key;
        public string data;
    }

    public class BinInsertSort
    {
        public const int MaxSize=100;
        public RecType[] R;
        public int Length;

        public BinInsertSort()    //初始化
        {
            R = new RecType[MaxSize];
            Length = 0;
        }

        public void Input()      //输入数据
        {
            Console.WriteLine("Please input some Integers:");
            string e = Console.ReadLine();
            string[] f = e.Split(new char[] { ',' });
            for (int i = 0; i < f.Length; i++)
            {
                R[i].Key = Convert.ToInt32(f[i]);
            }
            Length = f.Length;
        }

        public void BinInsertSort1()   //二分插入排序
        {
            int i, j, low, high, mid;
            RecType tmp;
            for (i = 1; i < Length; i++)
            {
                tmp = R[i];
                low = 0;
                high = i - 1;
                while (low <= high)
                {
                    mid = (low + high) / 2;
                    if (tmp.Key < R[mid].Key)
                        high = mid - 1;
                    else
                        low = mid + 1;
                }
                for (j = i - 1; j >= high + 1; j--)
                {
                    R[j + 1] = R[j];
                }
                R[high + 1] = tmp;
            }
        }

        public void Display()           //显示数据
        {
            for (int i = 0; i < Length; i++)
            {
                Console.Write(R[i].Key+" ");
            }
            Console.ReadKey();
        }
    }

<pre name="code" class="csharp"> static void Main(string[] args)
        {
            BinInsertSort L = new BinInsertSort();
            L.Input();
            L.BinInsertSort1();
            L.Display();
        }

    原文作者:查找算法
    原文地址: https://blog.csdn.net/erefeff/article/details/49563539
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞