數組排序

#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

相關文章
相關標籤/搜索
本站公眾號
   歡迎關注本站公眾號,獲取更多信息