数组排序

#include <vector>
#include <iostream>

using namespace std;

/*

给定一个包含1-n的数列,咱们经过交换任意两个元素给数列从新排序。求最少须要多少次交换,能把数组排成按1-n递增的顺序,
其中,数组长度不超过100。 
例如: 原数组是3,2,1, 咱们只须要交换1和3就好了,交换次数为1,因此输出1。 
	   原数组是2,3,1,咱们须要交换2和1,变成1,3,2,再交换3和2,变为1,2,3,总共须要的交换次数为2,因此输出2。
*/

int  run(int ArrayList[],int nLen)
{	
	int nNum = 0;
	for (int j = 1;j<nLen;++j)
	{
		int nMinPost = j-1;
		int nMin = ArrayList[nMinPost];
		for (int i = j;i<nLen;++i)
		{
			if(ArrayList[i]<nMin)
			{
				nMinPost = i;
			}
		}
		if(nMinPost != j-1)
		{
			int nData = ArrayList[j-1];
			ArrayList[j-1] = ArrayList[nMinPost];
			ArrayList[nMinPost] = nData;
			nNum++;
		}
	}
	return nNum;
}

void main()
{
	const int nLen = 3;
	int ArrayList [nLen] = {2,3,1};
	cout<<run(ArrayList,nLen)<<endl;
	system("pause");
}

 

本身写的仅供参考
ios

相关文章
相关标签/搜索
本站公众号
   欢迎关注本站公众号,获取更多信息