Index Sort
/************************************************************************/
/* given an array of integer, write a method to find indices m and n such that if
you sorted elements m through n, the entire array would be sorted. Minimize n-m
that is find the smallest such sequence
eg. input: 1,2,4,7,10,11,12,7,12,6,7,16,18,19
output: (3,10)*/
/* basic idea: using two stacks to remember the numbers, one is from head and the
other is from the tail. */
/************************************************************************/
#include <iostream>
#include <stack>
using namespace std;
int getindiceFhead(int a[], int length);
int getindiceFtail(int a[], int length);
void getIndices(int a[], int length) {
int m, n;
m = getindiceFhead(a, length);
n = getindiceFtail(a, length) - m;
cout<< "("<<m<<", "<<n<<")"<<endl;
}
int getindiceFhead(int a[], int length) {
stack<int> head;
int flag = 0;
head.push(a[0]);
for (int i = 1; i < length; i++)
{
if (a[i] >= head.top() && flag == 0)
{
head.push(a[i]);
}
while(a[i] < head.top() && head.size() > 1) {
flag = 1;
head.pop();
}
}
return head.size();
}
int getindiceFtail(int a[], int length) {
stack<int> tail;
int flag = 0;
tail.push(a[length-1]);
for(int i = length-2; i >= 0; i--) {
if (a[i] <= tail.top() && flag == 0)
{
tail.push(a[i]);
}
while(a[i] > tail.top() && tail.size() > 1) {
flag = 1;
tail.pop();
}
}
return length-tail.size();
}
Comments
Post a Comment