插入排序

插入排序:

对于数据空间减小的数据,采用直接插入排序。直接上代码。(编程环境 kali+sublime+gcc , 程序使用指针和数组两种方式(差别不大),和i和j之间微小的关系)
时间复杂度O(n^2),空间复杂度O(1)。

#include <iostream>
#include <stdlib.h>
using namespace std;

void insertsort(int *a,int n)
{
	int temp;
	for(int i=1;i<n;i++)
	{
		temp=*(a+i);
		int j=i-1;
		while(j>=0&&*(a+j)>temp)
		{
			*(a+j+1)=*(a+j);
			j--;
		}
		*(a+j+1)=temp;
	}
}

void insertsort2(int *a,int n)
{
	int temp;
	for(int i=1;i<n;i++)
	{
		temp=a[i];
		int j=i;
		while(j>0&&a[j-1]>temp)
		{
			
			a[j]=a[j-1];
			j--;
		}
		a[j]=temp;
	}
}

int insertloc(int *a,int low,int high,int value)
{
	if(low==high)
	{
		if(value>*(a+low))
			return (low+1);
		else
			return low;
	}
	int mid = (low + high)/2;
	if(value>*(a+mid)&&value>*(a+mid+1))
		insertloc(a,mid+1,high,value);
	else if(value<*(a+mid)&&value<*(a+mid+1))
		insertloc(a,low,mid,value);
	else
		return (mid+1);
}

void insertsortf(int *a,int n)
{
	int temp;
	int loc;
	for(int i=1;i<n;++i)
	{
		temp = *(a+i);
		int j=i-1;
		loc = insertloc(a,0,j,temp);
		cout<<"insert_location"<<loc<<endl;
		while(j>=loc)
		{
			*(a+j+1)=*(a+j);
			j--;
		}
		*(a+loc)=temp;
		for(int m = 0;m <= i;++m)  
            cout<<*(a + m)<<" ";  
        cout<<endl;  
	}
}

int main(int argc,char *argv[])
{
	int *arr;
	int num;
	cout<<"please input the sum of arr"<<endl;
	cin>>num;
	arr = (int *)malloc(num*sizeof(int));
	cout<<"please input the array!\n";
	for(int i=0;i<num;i++)
	{
		cin>>*(arr+i);
	}
	cout<<"\n";
	for(int j=0;j<num;j++)
	{
		cout<<*(arr+j)<<"\t";
	}
	cout<<"\n";
	//insertsort(arr,num);
	//insertsort2(arr,num);
	insertsortf(arr,num);
	for(int j=0;j<num;j++)
	{
		cout<<*(arr+j)<<"\t";
	}
	cout<<"\n";
	free(arr);
	return 0;
}

运行截图:




二分法运行截图:



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值