Home » Java » The shortest sort

The shortest sort



For an unordered array, A, design an algorithm that calculates the length of the shortest subarray to be sorted.



Given an integer array A, and its size n, return the length of the shortest subarray.



Test example:


[1,5,3,4,2,6,7], 7


returns: 4



Analysis of

/*:


> the minimum array array to order, the starting point start array, the end point end


< If an array is ordered, sequentially traversing the array, the latter is always greater than the previous monotonically increasing


A[i+1] that monotonicity change array starting point start = i


if A[i]


> gets the minimum value from [start, end], min maximum max


< [0, N] A[i]>min gets start


< [N, 0] A[i]


, public, int, findShortest (int[], A, int, n) {


int, start = 0;


int, end = 0;


for (int, I = 0; I < n-1; i++) {


if (A[i]>A[i+1]) {


start = I;


break;


}


}


for (int = I = n-1; I >0; i--) {


if (A[i]


end = I;


break;


}


}


int = Integer.MAX_VALUE; min;


int = Integer.MIN_VALUE; max;


for (int = I = start; I <=end; i++) {


min = min>A[i] = A[i]: min;


max = max


}


for (int, I = 0; I < n; i++) {


if (A[i]>min) {


start = I;


break;


}


}


for (int = I = n-1; I >=0; i--) {


if (A[i]


end = I;


break;


}


}


return end - start +1;


}


title to http://www.nowcoder.com/practice/a6926700bd424820bd73777f1cb2ef60? Rp=2&ru=/activity/oj&qru=/ta/2016test/question-ranking source:

Latest