直接插入排序

#include<iostream.h>
#include<string.h>
#include<vector>
#include<bitset>
using namespace std;

int main()
{
	vector<int> tt;
	int a;
	cout<<"Please input some numbers( q to quit): "<<endl;
	while((cin>>a)&&a!='q')
	{
		tt.push_back(a);
		cin.get();
	}
	int temp;
	for(vector<int>::iterator iter=tt.begin()+1;iter!=tt.end();iter++)
	{
		for(vector<int>::iterator iter1=iter-1;iter1!=tt.begin()-1;iter1--)
		{
			if(*iter<*iter1)
			{
				while((*iter<*(iter1--))&&(iter1!=tt.begin()-1));
				temp=*iter;
				for(vector<int>::iterator iter2=iter;iter2!=(iter1+1);iter2--)
				{
					*iter2=*(iter2-1);
				}
				*(iter1+1)=temp;
			}
			break;
		}
	}
	for(iter=tt.begin();iter!=tt.end();iter++)
		cout<<*iter<<" ";
	cout<<endl;
	return 0;
}

 修改后:

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

int main()
{
	vector<int> tt;
	int a;
	cout<<"Please input some numbers( q to quit): "<<endl;
	while((cin>>a)&&a!='q')
	{
		tt.push_back(a);
		cin.get();
	}
	for(vector<int>::iterator iter=tt.begin()+1;iter!=tt.end();iter++)
	{
		vector<int>::iterator iter1=iter-1;
		int temp=*iter;
		while(temp<*iter1)
		{
			*(iter1+1)=*iter1;
			iter1--;
		}
		*(iter1+1)=temp;
	}
	for(iter=tt.begin();iter!=tt.end();iter++)
		cout<<*iter<<" ";
	cout<<endl;
	return 0;
}

 再次修改:

#include<iostream.h>
#include<vector>
using namespace std;
void InsertSort(vector<int> &pp);
void Print_Result(vector<int>::const_iterator beg,vector<int>::const_iterator end);

void InsertSort(vector<int> &pp)
{
	for(vector<int>::iterator iter=pp.begin()+1;iter!=pp.end();iter++)
	{
		vector<int>::iterator iter1=iter-1;
		int temp=*iter;
		while(temp<*iter1)
		{
			*(iter1+1)=*iter1;
			iter1--;
		}
		*(iter1+1)=temp;
	}
}
void Print_Result(vector<int>::const_iterator beg,vector<int>::const_iterator end)
{
	while(beg!=end)
	{
		cout<<*beg++<<" ";
	}
}
int main()
{
	vector<int> tt;
	int a;
	cout<<"Please input some numbers( q to quit): "<<endl;
	while((cin>>a)&&a!='q')
		tt.push_back(a);
	InsertSort(tt);
	Print_Result(tt.begin(),tt.end());
	return 0;
}

再来个C语言的: 

#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#define TestNum 10
#define ArraySize 15
void InsertSort(int a[],int n);
int main()
{
	int a[ArraySize];
	srand((unsigned)time(NULL));
	for(int i=0;i<TestNum;i++)
	{
		printf("第%d次测试用例:\n",i+1);
		printf("排序前:");
		for(int j=0;j<ArraySize;j++)
		{
			a[j]=rand()%100;
			printf("%d  ",a[j]);
		}
		printf("\n");
		InsertSort(a,ArraySize);
		printf("排序后:");
		for(int k=0;k<ArraySize;k++)
		{
			printf("%d  ",a[k]);
		}
		printf("\n\n");
	}
	return EXIT_SUCCESS;
}
void InsertSort(int a[],int n)
{
	for(int j=1;j<n;++j)
	{
		int temp=a[j];
		int i=j-1;
		while(i>=0&&temp<a[i])
		{
			a[i+1]=a[i];
			--i;
		}
		a[i+1]=temp;
	}
}

 

其他小问题: 通常,函数不应该有vector或其他标准库容器类型的形参。调用含有普通的非引用vector形参的函数将会复制vector的每一个元素。C++程序员倾向于通过传递指向容器中需要处理的元素的迭代器来传递容器。

posted @ 2011-11-08 10:44  shiney  阅读(195)  评论(0编辑  收藏  举报