algorithm - Arrange the list in sequence -


i have list {10,5,3,9,12}. need convert {3,1,0,2,4}.i mean assign 0 smallest value,1 next smallest value on.

my code:

     list = {2,3,10,5,1};      (int =list.count-1; >= 0 ; i--)         {              var maxno = list.max();             var smallindex = list.indexof(maxno);             list[smallindex] = * -1;          }         (int = 0; < list.count; i++)         {             list[i] = list[i] * -1;         }         // prints {1,2,4,3,0} 

note: list contain positive numbers only.

is above code fine. need on this.

your algorithm works list of non-negative integers, others have noted, it's not efficient because of repeated max calculation.

i'm not sure i'm adding here, dan d's answer correct, maybe little more explanation bit ...

what you're looking in example of {2,3,10,5,1} mapping {1,2,4,3,0} list of indices original list occupy in sorted list.

the natural way sorting, indexing, , "unsorting" follows (and implemented in dan d's terser solution):

add index column original data:

{2,3,10,5,1} => {(2,0), (3,1), (10,2), (5,3), (1,4)} 

sort original column:

{(2,0), (3,1), (10,2), (5,3), (1,4)} => {(1,4), (2,0), (3,1), (5,3), (10,2)} 

add another index column:

{(1,4), (2,0), (3,1), (5,3), (10,2)} => {(1,4,0), (2,0,1), (3,1,2), (5,3,3), (10,2,4)} 

get original order sorting on first index column:

{(1,4,0), (2,0,1), (3,1,2), (5,3,3), (10,2,4)} => {(2,0,1), (3,1,2), (10,2,4), (5,3,3), (1,4,0)} 

drop original column , first index column, keeping index added in middle, has been put right position:

{(2,0,1), (3,1,2), (10,2,4), (5,3,3), (1,4,0)} => {1,2,4,3,0} 

this strategy work regardless of data type of original list, long it's can sorted.

as problem has involve sorting, doubt can better efficiency. adding , dropping columns linear, , sorting twice not worse sorting once.


Comments

Popular posts from this blog

c++ - Is it possible to compile a VST on linux? -

java - Output of Eclipse is rubbish -

jquery - Confused with JSON data and normal data in Django ajax request -