#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"); }
自己写的仅供参考