题目1:
给出一个序列,只交换相邻两数,使得序列升序排列,求出最少交换次数。
思路:
如果说只是交换相邻两个数字。那么就是这个序列的逆序数。
1.假设序列个数为n,我们先把最大的数换到最后,因为是相邻数字交换,所以把最大数交换到最后,需要交换的次数为最大数后的数字个数。
2.当完成最大数的交换后,可以将最大数从序列中划去不管了,即此时序列个数为n-1了,我们再在该序列中找到一个最大数,进行相同操作。
3.所以使整个序列有序的交换次数为,这个序列的所有逆序总数。
比如4,3,2,1。
(4,3) (4,2) (4,1),有3个逆序,交换后 3,2,1,4
(3,2) (3,1),有2个逆序,交换后2,1,3,4
(2,1),有1个逆序,交换后1,2,3,4
用归并的方法写了个。
#include<iostream>
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
using namespace std;
int cnt;
int arr[1005];
void Merge(int* arr,int* tmp,int left,int right,int rightEnd)
{
int leftEnd = right - 1;
int start = left;
while (left <= leftEnd && right <=