Skip to content

Commit fc990e0

Browse files
committed
Smallest subarray sorting which sorts array
1 parent 0da2929 commit fc990e0

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed

Diff for: arrays/UnsortedSubArray.rb

+70
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
#Given an unsorted array,find the minimum length of subarraay,sorting which sorts the whole array.
2+
#Time-complexity: O(n),Auxiliary-space:O(1)
3+
=begin
4+
Algorithm: Scan left to right and find first index where next element is less than current,let it be l
5+
(if l==a.length-1 it is already sorted),similarly scan right to left and search first index
6+
where previous element is larger than current,let it be r.Now search for min and max in l to r,
7+
now from 0 to l-1 find first element which is greater than min(let it be i) and
8+
from r+1 to a.length-1 find first element which is less than max.(let it be j)
9+
set l= i and r=j
10+
minimum length= r-l+1
11+
start=l
12+
end=r
13+
=end
14+
def unsorted_sub(a)
15+
n=a.length
16+
l=0
17+
r=n-1
18+
for i in 0...n-1
19+
if a[i]>a[i+1]
20+
l=i
21+
break
22+
else
23+
l+=1
24+
end
25+
end
26+
return "The complete array is sorted" if l==n-1
27+
28+
for i in (n-1).downto(1)
29+
if a[i]<a[i-1]
30+
r=i
31+
break
32+
else
33+
r-=1
34+
end
35+
end
36+
37+
min_i,max_i=find_minmax(a,l,r)
38+
39+
for i in 0...l
40+
if a[i]>a[min_i]
41+
l=i
42+
break
43+
end
44+
end
45+
46+
for i in (n-1).downto(r+1)
47+
if a[i]<a[max_i]
48+
r=i
49+
break
50+
end
51+
end
52+
return "Length: #{r-l+1}, Starting index: #{l}, Ending index: #{r}"
53+
end
54+
55+
def find_minmax(a,lo,hi)
56+
min=max=lo
57+
for i in (lo+1)..hi
58+
if a[i]>a[max]
59+
max=i
60+
elsif a[i]<min
61+
min=i
62+
else
63+
next
64+
end
65+
end
66+
return min,max
67+
end
68+
69+
unsorted_sub([15, 16, 21, 30, 25, 41, 28, 39, 58]) # => Length: 5, Starting index: 3, Ending index: 7
70+
unsorted_sub([1,2,3,4,5,6]) # => The complete array is sorted

0 commit comments

Comments
 (0)