Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort an array which alternates monotonically

Tags:

arrays

sorting

There is an array which is monotonically increasing for some time, then decreasing, again increasing, ...etc, like [1,2,3,4,5,3,1,-1,-3,2,5,67,90,8,7,3,0]. What would be the best way to sort this array? Some related question in Stackoverflow suggested K-Way Merge Sort, although no implementation details were provided.

So what would be the ideal way to sort it? Will any slick method provide significantly better performance than the good old O(N*log N) given by quicksort, so as to merit its use? If K-Way Merge Sort is the thing to do, please provide some implementation detail, I couldn't find one on Internet!

like image 711
SexyBeast Avatar asked Oct 27 '12 21:10

SexyBeast


People also ask

Does sort mutate array?

The sort() method returns a reference to the original array, so mutating the returned array will mutate the original array as well.

Is sort () destructive?

sort() is a list type method. sort() is a destructive process that sorts the original list in place.

How do you sort an array in Rpgle free format?

Free-Form SyntaxThe array-name operand is the name of an array to be sorted. The array is sorted into sequence (ascending or descending), depending on the sequence specified for the array on the definition specification. If no sequence is specified, the array is sorted into ascending sequence.

How do you sort an array without changing the array?

To sort an array, without mutating the original array:Call the slice() method on the array to get a copy. Call the sort() method on the copied array. The sort method will sort the copied array, without mutating the original.


2 Answers

You want Timsort, which exploits natural runs.

like image 53
A. Webb Avatar answered Oct 20 '22 19:10

A. Webb


I suppose a natural mergesort with preprocessing will do it in O(n).

  1. Reverse the order in the descending subarrays - O(n) total
  2. Do a natural mergesort - O(n): http://www.algorithmist.com/index.php/Merge_sort#Natural_mergesort
like image 1
SomeWittyUsername Avatar answered Oct 20 '22 17:10

SomeWittyUsername