Sort months ( with strings ) algorithm

前端 未结 10 1269
深忆病人
深忆病人 2021-01-18 03:42

I have this months array:

[\"January\", \"March\", \"December\" , \"October\" ]

And I want to have it sorted like this:

[\"         


        
10条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-18 04:16

    Thanks all for the suggestions, I would like to mark you all as accepted.

    Here's the resulting code:

    // correct order 
    months as String[] = ["jan", "feb", "mar", "apr", "may", "jun",
                          "jul", "aug", "sep", "oct", "nov", "dec"]
    // my unsorted months 
    myMonths as String[] = ["mar", "dec", "jul", "jan", "sep"]
    
    // poor substitute for Map
    mappedIndex as Int[]
    
    // create an array with the corresponding index 
    for each m in myMonths do
        i as Int = 0;
        for each month in months do 
           if m == month then 
               mappedIndex[] = i // no break, so I should use "else"
           else
              i = i + 1
           end
        end
    end
    
    // At this point mapped index has the same order as my "unsorted" array
    // in this case [2,11,5,0,8]
    
    // Fortunately this language has "sort" otherwise I would jump out of the window
    mappedIndex.sort()
    
    // create a new array to hold the sorted values
    myMonthsSorted as String[]
    
    // and fill it with the correct value
    for each i in mappedIndex do 
       myMonthsSorted[] = months[i]
    end
    

提交回复
热议问题