Comparable接口可以实现对象数组排序,也就可以对整型数组进行直接排序:
import java.util.*;
class Node implements Comparable<Node> {
private int value;
public Node(int value) {
this.value = value;
}
@Override
public int compareTo(Node node) {
if (this.value == node.value) {
return 0;
} else {
return this.value > node.value ? 1 : -1;
}
}
public static void sortInt(int[] a) {
Node[] node = new Node[a.length];
for(int i = 0; i < a.length; i ++) {
node[i]=new Node(a[i]);
}
Arrays.sort(node);
for(int i = 0; i < a.length; i ++) {
a[i] = node[i].value;
}
}
public static void main(String[] args) {
int[] a = {1, 4, 5, 7, 6, 5, 9, 12, 34, 23};
sortInt(a);
for(int i = 0; i < a.length; i ++) {
System.out.print(a[i] + " ");
}
}
}
输出结果:1 4 5 5 6 7 9 12 23 34