package com.varicom.test.test;
import java.util.List;
import org.junit.Test;
import com.google.common.collect.Lists;
public class SortTest {
@Test
public void testSort() {// 10,8,5,25,1000,1
List<SortObject> list = Lists.newArrayList();
list.add(new SortObject(10));
list.add(new SortObject(8));
list.add(new SortObject(5));
list.add(new SortObject(25));
list.add(new SortObject(1000));
list.add(new SortObject(1));
list.add(new SortObject(6));
showData(list);
sort(list);
showData(list);
}
public void showData(List<SortObject> list) {
for (int i = 0; i < list.size(); i++) {
System.out.print(list.get(i).getAge() + ",");
}
System.out.println();
}
public void sort(List<SortObject> list) {
for (int i = 0; i < list.size() - 1; i++) {
if (list.get(i).compareTo(list.get(i + 1)) > 0) {// 要调换位置
changePosition(list, i, i + 1);
for (int j = i; j > 0; j--) {
if (list.get(j - 1).compareTo(list.get(j)) > 0) {
changePosition(list, j - 1, j);
} else {
break;
}
}
}
}
}
public void changePosition(List<SortObject> list, int i, int j) {
SortObject temp = null;
temp = list.get(i);
list.set(i, list.get(j));
list.set(j, temp);
}
}
package com.varicom.test.test;
public class SortObject {
private int age;
public SortObject() {
super();
}
public SortObject(int age) {
super();
this.age = age;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int compareTo(SortObject o) {
System.out.println("a:" + this.age + ",b:" + o.age + " =:" + (this.age - o.age));
return this.age - o.age;
}
}