【发布时间】:2021-08-30 13:02:09
【问题描述】:
我正在尝试验证返回的列表是否已排序,但通过预定义的排序算法。如果列表未排序,那么我应该通过自定义排序对其进行排序。
我已经实现了自定义排序功能,但是我想验证检索到的列表是否根据自定义排序进行排序。
这是自定义排序的代码:
public static void customSort(final String order, String[] array){
String[] alphabets = {"!", "@", "#", "$", "%", "^", "&", "(", ")", "*", "+", ",", "-", "/",
"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "=",
"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z",
"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z",
"[", "]", "_"
};
String keyword = order;
for(int g = 0; g < alphabets.length; g++){
String one = alphabets[g];
if(!keyword.contains(one)){
keyword = keyword + one;
}
}
final String finalKeyword = keyword;
Arrays.sort(array, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
int pos1 = 0;
int pos2 = 0;
for (int i = 0; i < Math.min(o1.length(), o2.length()) && pos1 == pos2; i++) {
pos1 = finalKeyword.indexOf(o1.charAt(i));
pos2 = finalKeyword.indexOf(o2.charAt(i));
}
if (pos1 == pos2 && o1.length() != o2.length()) {
return o1.length() - o2.length();
}
return pos1 - pos2 ;
}
});
public static void main(String args[]){
final String order = "!@#$%^ ()*+,-/0123456789=abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ[]_";
customSort(order, arr);
}
【问题讨论】:
-
您写了“List”并用“arraylist”标记了这个问题,但是那个列表在哪里?你只使用数组。
-
检索到的数据是一个list/arraylist
-
" 如果列表没有排序,那么我应该通过自定义排序对其进行排序。"这意味着您信任自定义排序的结果 - 所以只需对“检索到的列表”进行排序(您没有很好地解释这一点,但假设您是从另一个来源获得的) - 如果您需要知道“检索到的列表”是否是未根据自定义排序进行排序,然后只需将检索到的列表与排序列表进行比较。
-
谢谢大家。我应该更多地解释这个问题
标签: java arrays sorting arraylist