given an array of size N. we're required to sort the array with adjacent swaps only, every swap has a cost |a-b| where a,b are the two adjacent integers. Task is to minimize the maximum costs of all the operations required to sort an array. (Is the task to store the maximum cost of any adjacent swap so far?)
i implemented merge sort but it accounts for any two integers being swapped and bubble sort just causes execution timeout.
#include <iostream>
#include <stdlib.h>
using namespace std;
//nLog(n) time O(n) space
int merging(int arr[],int l,int mid,int h){
int k = 0, i = l, j = mid+1;
int temp[h - l + 1];
int c = 0;
while(i <= mid && j <= h){
if(arr[i]<=arr[j]) //no swap required for higher val
{
temp[k++] = arr[i++];
}
else{
//swap took place
c = max(c,arr[i] - arr[j]);
temp[k++] = arr[j++];
}
}
while(i <= mid){
temp[k++] = arr[i++];
}
while(j <= h){
temp[k++] = arr[j++];
}
//update the initial array with temp array 0th indexing
for(int i = l; i < h; i++){
arr[i] = temp[i-l];
}
return c;
}
int mergeSort(int arr[],int l,int h){
int c = 0;
if(l<h){
int mid = l + (h-l)/2;
c = max(mergeSort(arr,l,mid),c);
c = max(mergeSort(arr,mid+1,h),c);
c = max(merging(arr,l,mid,h),c);
}
return c;
}
int MinSwapCountUtil(int arr[],int n){
return mergeSort(arr,0,n-1);
}
int main(void){
int arr [] = {4,2,5,1,3};
int n = sizeof(arr)/sizeof(arr[0]);
cout<<MinSwapCountUtil(arr,n);
return 0;
}
Aucun commentaire:
Enregistrer un commentaire