我有输入
1 31 22 32 11 13 12
那我想得到这样的结果
1
11
31
12
22
32
13
我应该使用哪种方法? 谢谢
答案 0 :(得分:1)
为此(Java 8),您可以使用sort
,并稍加修改比较器:
yourList.sort(Comparator.comparingInt(number -> number % 10));
答案 1 :(得分:0)
您的程序是按最后一位,然后按数值排序。
您可以这样做:
Comparator<Integer> c = (a, b) -> {
int n = Integer.compare(a % 10, b % 10);
if (n != 0) {
return n;
}
return Integer.compare(a, b);
};
Stream.of(1, 31, 22, 32, 11, 13, 12).sorted(c).forEach(System.out::println);
答案 2 :(得分:0)
执行此操作的一种方法是先对数字进行排序,例如quicksort,然后对数字的最后一位(%10)进行稳定排序,例如插入排序;
public class Main {
public static void main(String[] args) {
int[] numbers = {1,31,22,32,11,13,12};
sort(numbers,0,numbers.length-1);
sort(numbers);
for(int i : numbers) {
System.out.println(i);
}
}
static int partition(int arr[], int low, int high)
{
int pivot = arr[high];
int i = (low-1);
for (int j=low; j<high; j++)
{
if (arr[j] <= pivot)
{
i++;
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
int temp = arr[i+1];
arr[i+1] = arr[high];
arr[high] = temp;
return i+1;
}
static void sort(int arr[], int low, int high)
{
if (low < high)
{
int pi = partition(arr, low, high);
sort(arr, low, pi-1);
sort(arr, pi+1, high);
}
}
static void sort(int arr[])
{
int n = arr.length;
for (int i=1; i<n; ++i)
{
int key = arr[i];
int j = i-1;
/* Move elements of arr[0..i-1], that are
greater than key, to one position ahead
of their current position */
while (j>=0 && arr[j]%10 > key%10)
{
arr[j+1] = arr[j];
j = j-1;
}
arr[j+1] = key;
}
}
}
从https://www.geeksforgeeks.org捏起的排序算法
答案 3 :(得分:0)
您可以使用以下compare
方法获得任意长度正整数的所需顺序:
public int compare(Integer i1, Integer i2)
{
for(int c; i1 != 0 && i2 != 0; i1/=10, i2/=10)
{
if((c = Integer.compare(i1 % 10, i2 % 10)) != 0)
return c;
}
return Integer.compare(i1, i2);
}
有趣的是,这是每个数字的反向字符串表示形式的字典顺序,因此您可以执行以下操作:
String[] s = "1 31 22 32 11 13 12".split(" ");
for(int i=0; i<s.length; i++) s[i] = new StringBuilder(s[i]).reverse().toString();
Arrays.sort(s);
for(int i=0; i<s.length; i++) s[i] = new StringBuilder(s[i]).reverse().toString();
System.out.println(Arrays.toString(s));
输出:
[1, 11, 31, 12, 22, 32, 13]
顺便说一句,在Java中没有简单的内置方法来返回String
的倒数是多么疯狂?