编写一个函数,当且仅当a[0:n-1]有序时,返回值为true

主要用来判断一个数组是否有序,并且用的是模版函数。
#include<iostream>
using namespace std;
template <class T>
T is_sorted(T *a,const T n)
{
	int f=1;
	int ff=1;
	for(int i=0;i<n;i++)
	{
		if(a[i]<a[i+1])
			f=0;
		if(a[i]>=a[i+1])
			ff=0;
	}
	if(f+ff==0)
		return -1;
	else
		return true ;
}
void main()
{
	int a[]={1,2,3,4,5,6,7};
	int x=is_sorted(a,6);
	cout<<x<<endl;
	if(x==-1)
	{
		cout<<"无序"<<endl;
	}
	else
	{
		cout<<"有序"<<endl;
	}
	system("pause");
}

猜你喜欢

转载自blog.csdn.net/qq_36631272/article/details/79929668