use*_*481 5 arrays sorting algorithm
给定正整数的数组A [1 ... N],您必须按以下方式按升序对其进行排序:在每个操作中,选择任意2个相等长度的非重叠子数组并交换它们.即,选择两个子阵列A [i ...(i + k-1)]和A [j ...(j + k-1)],使得i + k-1 <j并且交换A [i ]与A [j]的,A [1 + 1] A [J + 1] ...和A [1 + K-1]与A [J + K-1].
Example:
For N=6
6 7 8 1 2 3
Only one operation is needed as after swapping (6 7 8) and (1 2 3 ) sub arrays
we can get 1 2 3 6 7 8 , that is sorted.
Run Code Online (Sandbox Code Playgroud)
我们如何才能以最有效的方式确定掉期的最小数量? 消息来源: https ://www.hackerearth.com/problem/approximate/swap-and-sort/
小智 1
#include <iostream>
using namespace std;
void swaparr(int a[],int l,int r,int n) {
for(int i=l,j=r;i<=l+n&&j<=r+n;i++,j++)
swap(a[i],a[j]);
}
int findMax(int a[],int n) {
int index = 0;
for(int i=1;i<=n;i++)
if(a[i] > a[index])
index = i;
return index;
}
void sort(int a[],int n) {
for(int r=n-1;r>;0;r--) {
int index = findMax(a,r);
if(index != r) {
int l = min(r-index-1,index);
swaparr(a,index-l,r-l,l);
}
}
}
int main() {
int a[] = {7,23,8,234,3,6,41,334};
int n = 8;
sort(a,n);
for(int i=0;i<n;i++)
cout<<a[i]<<" ";
return 0;
}
Run Code Online (Sandbox Code Playgroud)
逻辑:找到每个操作中的最大元素并执行交换,以使最大元素到达末尾。执行此操作 N 次,每次将数组大小减少 1,并旨在每次操作中拥有最大元素。没有必要进行 N 次交换。仅当最大元素不在其位置时才执行交换。T = O(n2)