3

I'm programming a function for a TI-Nspire, so I can't use the builtins from inside a function. What is the most generally efficient algorithm for sorting a list of numbers without modifying the list itself? (recursion and list-splitting are fair game, as is general use of math.)

AstroCB
  • 12,337
  • 20
  • 57
  • 73
muhmuhten
  • 3,313
  • 1
  • 20
  • 26
  • 1
    I suppose you tried calling `SortA` on a list, but the calculator won't let you do that because it's in a function? Sigh. This problem exists on the TI-68k as well. – Joey Adams May 18 '10 at 21:41
  • precisely the problem. the 83-series doesn't have this problem, but also doesn't have builtin argument passing. – muhmuhten May 18 '10 at 22:36
  • If it helps, I noticed these sorting functions on ticalc.org: http://www.ticalc.org/archives/files/fileinfo/429/42964.html – Joey Adams Jun 18 '10 at 06:26

2 Answers2

3

Mergesort is straightforward, simple, efficient, and stable: split the list, sort recursively, and merge the results.

To be more specific, mergesort takes O(N log N), which is asymptotically optimal. Also, in practice (with both algorithms modified to sort short sublists with a special-purpose sort), mergesort can be a close competitor to the modified quicksort used in the C/C++ standard libraries.

Edit: unlike in-place sorts like quicksort and insertion sort, mergesort requires auxiliary memory, and is simplest to implement by copying rather than swapping.

comingstorm
  • 25,557
  • 3
  • 43
  • 67
  • If you could modify the list then I would suggest quicksort because it uses less memory on average, but mergesort is definitely the way to go in this case. – Justin Peel May 18 '10 at 22:44
  • @Justin Peel: Notice also that a naive implementation of quick sort will easily become slower than merge sort for large data. AFAIK, efficient quick sort means quick sort + cleaver choice of pivot + (possibly) fall-back to heap-sort (see intro sort). Otherwise, in my experience, pure quick sort does not perform well compared to merge sort. – Giorgio Dec 25 '12 at 20:28
0

Timsort is used in python and java SE 7. It takes the best of merge sort and insertion sort. Insertion sort is O(n^2) but with small lists of numbers it is faster than merge sort!

So you can use this as a generic sorting algorithm as stated here

Community
  • 1
  • 1
Enrique
  • 9,920
  • 7
  • 47
  • 59
  • 1
    didn't feel like reading it all, but considering you said it takes the best of merge and insert sort, and insertion sorts modify the value inplace, does timsort require any inplace modification? – muhmuhten May 18 '10 at 22:38
  • 1
    Timsort is great, but I think far more complicated than is necessary for just getting a good sort on a calculator. – Justin Peel May 18 '10 at 22:45