Does sortrows always preserve the original ordering within sorting groups?

拜拜、爱过 提交于 2021-02-05 06:35:37

问题


MATLAB's sortrows function seems to leave ordering unchanged within each sorting group. Does anyone know whether this is actually true, as I cannot find any documentation supporting this.

Using MATLAB's provided example for sortrows:

A = {'Germany' 'Lukas'; 'USA' 'William'; 'USA' 'Andrew'; ...
'Germany' 'Andreas'; 'USA' 'Olivia'; 'Germany' 'Julia'} 

A = 

    'Germany'    'Lukas'  
    'USA'        'William'
    'USA'        'Andrew' 
    'Germany'    'Andreas'
    'USA'        'Olivia' 
    'Germany'    'Julia'  

and applying sortrows(A, [1])

ans = 

    'Germany'    'Lukas'  
    'Germany'    'Andreas'
    'Germany'    'Julia'  
    'USA'        'William'
    'USA'        'Andrew' 
    'USA'        'Olivia' 

see that in the original data, Germany in the first column is followed by Lukas, Andreas, Julia in the second column reading from top to bottom. This is preserved in the end result.

Is this behaviour guaranteed?


回答1:


Yes.

Matlab uses quick sort which is stable (if they don't employ some data specific optimizations). For the most part, I'd assume that Matlab uses stable sort, but cannot be sure without looking at the source.

Your best bet is contacting Matlab tech support to make sure that their sort algorithm is indeed stable, and if they have any plans to change that in the future.

sortrows uses the internal sort. You can read the source:

>> edit sortrows

edit: more info




回答2:


I don’t know if sortrows is stable, the docs don’t say (or I couldn’t find it in the docs).

But you can always enforce stability by adding a column with sorted integers, for example 1:N, and sort on this column as a second value (so sort on [1,3] if the new column is the 3rd one).




回答3:


Yes, that's what the 1 means. If you were to put in [1,2], it would sort the second row.



来源:https://stackoverflow.com/questions/32322908/does-sortrows-always-preserve-the-original-ordering-within-sorting-groups

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!