代码之家  ›  专栏  ›  技术社区  ›  David542

排序各种数据类型的算法[已关闭]

  •  -1
  • David542  · 技术社区  · 4 年前

    从概念上讲,我想对变量类型的单个列的数据进行排序,类似于在Excel中的做法:

    enter image description here

    在这里,我们可以看到数字在字符串之前排序,在布尔之前排序,在错误之前排序。所以,我希望在SQL中有一个这样的函数:

    SELECT * FROM table ORDER BY
      CASE WHEN type='number' THEN 0 WHEN type='string' THEN 1 /* ... */ END,
      SortFunction(variantData)
    

    以下是我想要实现的目标:

    • 这个 SortFunction 需要返回单个数据类型的值,例如字符串、数字或二进制类型。
    • 如果有必要,我可以限制函数中文本字段的长度(例如,如果我们有一个10000个字符的字符串,只需将其限制在前100个字符)。

    任何编程语言都可以,我更关心的是一种实现这种类似Excel的排序的技术。

    对于数字字段,我们可以保持原样,对于与日期/时间相关的字段,我们可以使用unix时间戳,但是对于字符串或二进制数据类型,我们应该如何使用它呢?

    1 回复  |  直到 4 年前
        1
  •  1
  •   Vishrant    4 年前

    将每个元素视为字节数组,并应用比较器:

    import java.util.Arrays;
    import java.util.Comparator;
    
    public class SortAnyObjects {
    
        public static void main(String[] args) {
    
            Object[] arr = {1, 'c', '&', "z", "testing", "hello world", '文',
                'Ã¥'};
    
            byte[][] a = new byte[arr.length][];    // <---- The column is not initialized
    
            for (int i = 0; i < arr.length; i++) {
                if (arr[i] instanceof Integer) {
                    a[i] = String.valueOf((int) arr[i]).getBytes();
                }
                else if (arr[i] instanceof Character) {
                    a[i] = String.valueOf((char) arr[i]).getBytes();
                }
                else {     // <---- Here expand your else condition as you expect the datatypes
                    a[i] = ((String) arr[i]).getBytes();
                }
            }
    
            Arrays.sort(a, new Comparator<byte[]>() {
                @Override
                public int compare(
                    final byte[] o1,
                    final byte[] o2
                ) {
                    if (o1 == null) {
                        return 1;
                    }
                    if (o2 == null) {
                        return -1;
                    }
                    if (o1 == o2) {
                        return 0;
                    }
    
                    if (o2.length > o1.length) {
                        return compare(o2, o1);
                    }
    
                    for (int i = 0; i < o1.length; i++) {
                        if (o1[i] == o2[i]) {
                            continue;
                        }
                        return Byte.compare(o1[i], o2[i]);
                    }
                    return 0;
                }
            });
    
            System.out.println(Arrays.toString(a));
    
            for (int i = 0; i < a.length; i++) {
                System.out.println(new String(a[i]));
            }
        }
    
    }