Sunday, August 18, 2013

find unsorted subarray

/* 19-6 Given an array of integers. 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). */


const int EMPTY_ARRAY = -2;
const int SORTED_ARRAY = -1;

pair<int,int> findUnsortedIndices(int [], int);
int findFirstUnsortedIndex(int [], int);
int findLastUnsortedIndex(int [], int);

pair<int,int> findUnsortedIndices(int arr[], int len){
    pair<int,int> indices;
    indices.first = findFirstUnsortedIndex(arr, len);
    indices.second = findLastUnsortedIndex(arr, len);
    return indices;
}

int findFirstUnsortedIndex(int arr[], int len){
    if (len == 0) {
        return EMPTY_ARRAY;
    }
    if (len == 1) {
        return SORTED_ARRAY;
    }
    stack<int> s;
    bool elementsInOrder = true;
    s.push(arr[0]);
    for (int i = 1; i < len; i++) {
        if (arr[i] >= s.top() && elementsInOrder) {
            s.push(arr[i]);
        } else {
            elementsInOrder = false;
            while (arr[i] < s.top()) {
                s.pop();
            }
        }
    }
    if ((int)s.size() == len) {
        return SORTED_ARRAY;
    }
    return (int)s.size();
}

int findLastUnsortedIndex(int arr[], int len){
    if (len == 0) {
        return EMPTY_ARRAY;
    }
    if (len == 1) {
        return SORTED_ARRAY;
    }
    stack<int> s;
    bool elementsInOrder = true;
    s.push(arr[len-1]);
    for (int i = len-2; i >= 0; i--) {
        if (arr[i] <= s.top() && elementsInOrder) {
            s.push(arr[i]);
        } else {
            elementsInOrder = false;
            while (arr[i] > s.top()) {
                s.pop();
            }
        }
    }
    if ((int)s.size() == len) {
        return SORTED_ARRAY;
    }
    return len - 1 - (int)s.size();
}

No comments:

Post a Comment