Sort strings and numbers in Ruby

后端 未结 6 1962
一生所求
一生所求 2020-12-08 12:48

I want to sort an array by strings first and then numbers. How do I do this?

6条回答
  •  伪装坚强ぢ
    2020-12-08 13:13

    If you are trying to sort Mixed case and numbers, only a few people on earth can do it outside of proprietary applications. It is a secret with a sucker punch. You must use a qsort which makes sorting easy until you mix cases (upper and lower case letters). Then college, books and internet leave you hanging. This hack worth its weight in gold and is the brass ring of programming for all reasons.

    To sort numbers with words you must convert numbers into string. You must presort using upper case. If you have the words "Ant", "ant" and "anT" on the less they should all point to the word "ANT" to the upper case sort list. You will then create a list (array) of just these three words ["Ant", "ant" and "anT"] and use qsort as a tie breaker to sort them.

    You then insert them into a final sorting array. It is fairly difficult by design. "A" is 65 on ascii and 'a' is 97 with lots of garbage characters between 'Z' and 'a'! It is no accident! It a conspiracy I tell you!

    You could create a sorting table the more sanely groups the characters like :

    A, a, B, b, C, c, D, d, E, e, F, f, G, g, H, h, I, i, J, j, K, k, L, l, M, m, N, n, ... 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 ...

    building the table around this block starting with " "(space) ascii 32 upto 128. you will probably want to reorder the numbers in sequence the A 65 is for example only.

    This makes it easier but will likely cause a performance hit being outside the macros of most programming languages. Good luck!

提交回复
热议问题