Reversing a sub-array of an array , in less than O(n) time

how can we reverse a subarray ( say from i-th index to j-th index ) of an array ( or any other data structure , like linked-list ( not doubly )), in less than O(n) time ? the O(n) time consumption is trivial.( I want to do this reversion many times on the array , like starting from the beginning and reversing it for n times (each time , going forward for one index and then reversing it again), so there should be a way ,which its amortized analysis would give us a time consumption less than O(n) , any idea ? thanks In advance :)


I think you want to solve this with a wrong approach. I guess you want to improve the algorithm as a whole, and not the O(n) reversing stuff. Because that's not possible. You always have O(n) if you have to consider each of the n elements.

As I said, what you can do is improve the O(n^2) algorithm. You can solve that in O(n): Let's say we have this list:

a b c d e

You then modify this list using your algorithm:

e d c b a
e a b c d

and so on.. in the end you have this:

e a d b c

You can get this list if you have two pointers coming from both ends of the array and alternate between the pointers (increment/decrement/get value). Which gives you O(n) for the whole procedure.

More detailed explanation of this algorithm:

Using the previous list, we want the elements in the follow order:

a b c d e
2 4 5 3 1

So you create two pointers. One pointing at the beginning of the list, the other one at the end:

a b c d e
^       ^
p1      p2

Then the algorithms works as follows:

1. Take the value of p2
2. Take the value of p1
3. Move the pointer p2 one index back
4. Move the pointer p1 one index further
5. If they point to the same location, take the value of p1 and stop.
   or if p1 has passed p2 then stop.
   or else go to 1.

Need Your Help

Significance of IE specific classes (ie8, ie9,..) in html tags for Open Graph

html5 internet-explorer facebook-opengraph opengraph

For open graph, I see several IE specific html tags at the top of several websites (including airbnb, fab, fashiolista), which are like these:

Rails 3, acts-as-taggable-on gem - how to get the most used tags?

ruby-on-rails-3 tags count acts-as-taggable-on

I use acts-as-taggable-on gem and would like to fetch 5 most used tags, how could I fetch them?

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.