您的位置:首页 > 其它

交换任意两个元素进行排序进行的最小交换次数

2018-03-22 00:09 330 查看
核心思路 :
原始数组  A: 8 3 5 1 0
最终数组  B:0 1 3 5  8 (已经排序了)
对数组排序,找到最终数组B的第i个(假设i=0)元素在原始数组A中的下标的位置4,然后将最终数组B元素B[0](B[0]在例子中就是元素0)放到原始数组A下标为0的地方,就把第一个元素的位置给搞定了.如果某一个元素()在最终数组B中的位置和在原始数组中的位置一样的话,就说明不用换位置,直接跳过.然后依次遍历(就是不断地进行i=1,2,3...)的情况,直到遍历结束.

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int findPosIndex(vector<int> nums, int target){

for (int i = 0; i <= nums.size() - 1; i++){
if (nums[i] == target){
cout << "pos: " << i << endl;
return i;
}
}
return -1;
}
vector<int> nums_ori;
void sortWithLeastExchange(vector<int> &nums){
nums_ori = nums;
int count = 0;
sort(nums.begin(), nums.end());

for (int i = 0; i < nums.size() - 1; i++){
int posIndex = findPosIndex(nums_ori, nums[i]);
if (posIndex == i) continue;
cout << "exhange: " << nums_ori[i] << ":" << nums_ori[posIndex] << endl;
swap(nums_ori[i], nums_ori[posIndex]);
for (int i : nums_ori)
cout << i << "\t";
count++;
}
cout << count << endl;
}

int main()
{
vector<int> nums{ 8,3,5,1,0 };

sortWithLeastExchange(nums);

system("pause");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐