自己写一个对对象内部数据的排序,有几点想法:
第一:参考comparable 的comparaTo()以及mergeSort()方法;
第二:参考arrays的sort方法
几个疑问:
第一:关于排序法的区别?耗费的时间?
第二:怎么做到算法的通用?
高手指点指点...
贴代码:
public interface Generator {
Object next();
}
package star20110427;
import java.util.Random;
import star20110426.Generator;
/**
* 二维数组排序
* @author *
*/
public class SimpleSort {
private static Random random = new Random();
private static Generator getGenerator(){
return new Generator(){
@Override
public Object next() {
return new Num(random.nextInt(100),random.nextInt(100));
}
};
}
private static Num[] getNums(int count){
Num[] nums = new Num[count];
for (int i = 0; i < nums.length; i++) {
nums[i] = (Num) getGenerator().next();
}
return nums;
}
public static void main(String[] args) {
Num[] nums = getNums(1000);
for (int i = 0; i < nums.length; i++) {
System.out.println(nums[i]);
}
for (int i = 0; i < nums.length; i++) {
for (int j = nums.length-1; j > i; j--) {
if (nums[i].i > nums[j].i) {
Num temp = nums[j];
nums[j] = nums[i];
nums[i] = temp;
}
if (nums[i].i == nums[j].i) {
if (nums[i].j > nums[j].j) {
Num temp = nums[j];
nums[j] = nums[i];
nums[i] = temp;
}
}
}
}
System.out.println("===================");
for (int i = 0; i < nums.length; i++) {
System.out.println(nums[i]);
}
}
}
class Num{
int i ;
int j;
public Num(int i,int j) {
this.i = i;
this.j = j;
}
public int getI() {
return i;
}
public void setI(int i) {
this.i = i;
}
public int getJ() {
return j;
}
public void setJ(int j) {
this.j = j;
}
@Override
public String toString() {
return "i="+i+" j="+j;
}
}