您的位置:首页 > 其它

使序列有序的最少交换次数(minimum swaps)

2017-02-22 07:12 411 查看
题目描述:(minimum swaps)

Given a sequence, we have to find the minimum no of swaps required to sort the sequence.

 

分析:

formula:  no. of elements out of place  -  "cycles" in the sequence

 

A cycle is a set of elements, each of which is in the place of another.  So in example sequences { 2, 1, 4, 3}, there are two cycles: {1, 2} and {3, 4}.  1 is in the place where 2 needs to go, and 2 is in the place where 1 needs to go 1, so they are a cycle;
likewise with 3 and 4.

 

The sequences {3, 2, 1, 5, 6, 8, 4, 7 }also has two cycles: 3 is in the place of 1 which is in the place of 3, so {1, 3} is a cycle; 2 is in its proper place; and 4 is in the place of 7 which is in the place of 8 in place of 6 in place of 5 in place of 4,
so {4, 7, 8, 6, 5} is a cycle.  There are seven elements out of place in two cycles, so five swaps are needed.

 

实现:

e.g. { 2, 3, 1, 5, 6, 4}

231564 -> 6 mismatch

two cycles -> 123 and 456

swap 1,2 then 2,3, then 4,5 then 5,6 -> 4 swaps to sort

 

Probably the easiest algorithm would be to use a bitarray. Initialize it to 0, then start at the first 0. Swap the number there to the right place and put a 1 there. Continue until the current place holds the right number. Then move on to the next 0

 

Example:

231564

000000

-> swap 2,3

321564

010000

-> swap 3,1

123564

111000

-> continue at next 0; swap 5,6

123654

111010

-> swap 6,4

123456

111111

-> bitarray is all 1's, so we're done.

 

#include <iostream>
#include <algorithm>

using namespace std;

template <typename T>
int GetMinimumSwapsForSorted(T seq[], int n)
{
bool* right_place_flag = new bool
;
T* sorted_seq = new T
;
int p ,q;
////
copy(seq, seq + n, sorted_seq);
sort(sorted_seq, sorted_seq + n);    ////可采用效率更高的排序算法
// 初始化bitarray
for(int i = 0; i < n; i++)
{
if(seq[i] != sorted_seq[i])
right_place_flag[i] = false;
else
right_place_flag[i] = true;
}
////
p = 0;
int minimumswap = 0;
while(1)
{
while(right_place_flag[p])
p++;
q = p + 1;
// 在已排好序的数组中找到和未排好序的元素,此种找法只对无重复序列能得出minimum swaps
while(q < n)
{
if(!right_place_flag[q] && sorted_seq[q] == seq[p])
break;
q++;
}

if(q >= n || p >= n)
break;
right_place_flag[q] = true;
// 对调后正好在排好序数组的位置上,则bitarray中的那位也置为true
if(seq[q] == sorted_seq[p])
right_place_flag[p] = true;
swap(seq[p], seq[q]);
minimumswap++;
}

delete[] sorted_seq;
delete[] right_place_flag;

return minimumswap;
}

int _tmain(int argc, _TCHAR* argv[])
{
int seq[] = {3, 2, 1, 5, 6, 8, 4, 7 };//{2,3,1,5,6,4};//{2,3,2,4,7,6,3,5};
int n = sizeof(seq) / sizeof(int);
cout<<"minimum swaps : "<<GetMinimumSwapsForSorted(seq, n)<<endl;

system("pause");
return 0;
}


 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: