一句话概括:循环每次从未排序里选择一个最小或的最大的元素依次放好,直到最后(没有未排序的了)。
1.int型数组选择排序
import java.util.Random;public class test1 { private static int a[]; public static void main(String[] args) { produceData(10,1,10); print(); sort(); print(); } //产生数据 private static void produceData(int n,int min,int max ) { a = new int[n]; Random random = new Random(); for(int i= 0;i2.使用Comparable接口实现各种数据类型排序a[j]) minindx = j; } int tmp = a[minindx]; a[minindx] = a[i]; a[i] = tmp; } } private static void print() { int n = a.length; for(int i=0;i
自定义的Student类:
import java.util.Comparator;public class Student implements Comparable排序算法{ public String name; public int score; public Student(String name, int score) { super(); this.name = name; this.score = score; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getScore() { return score; } public void setScore(int score) { this.score = score; } @Override public String toString() { return "Student [name=" + name + ", score=" + score + "]"; } @Override public int compareTo(Student o) { if(this.getScore()>o.getScore()) return 1; else if(this.getScore()
import java.util.Comparator;import java.util.Random;public class test1 { public static void main(String[] args) { Student[] stus = produceData(); print(stus);//打印原来顺序 sort(stus); print(stus); //比较Double类型(也实现了Comparable接口) Double[] d = {3.14,3.11,3.99}; sort(d); print(d); } //产生数据 private static Student[] produceData() { Student[] stus = new Student[4]; stus[0] = new Student("A",66); stus[1] = new Student("B",90); stus[2] = new Student("C",80); stus[3] = new Student("D",100); return stus; } //排序 private static void sort(Comparable[] arry) { int n = arry.length; for(int i=0;i3.编写一个类来测试排序算法运行时间(利用反射和系统时间实现)
import java.lang.reflect.Method;public class SortTestHelper { public static void testSort(String sortClassName,Comparable[] arry) { try { //告诉类名即可获取class对象 Class sortClass = Class.forName(sortClassName); //指明方法名和参数列表就可以获取 //getDeclaredMethod()获取的是类自身声明的所有方法,包含public、protected和private方法。 //getMethod()获取的是类的所有共有方法,这就包括自身的所有public方法,和从基类继承的、从接口实现的所有public方法。 Method sortMethod = sortClass.getDeclaredMethod("sort", new Class[]{Comparable[].class}); Object[] params = new Object[]{arry}; long startTime = System.currentTimeMillis(); //第一个参数是调用哪个对象实例的此方法,静态就写null,第二个为方法参数 sortMethod.invoke(null, params); long overTime = System.currentTimeMillis(); System.out.println("耗时:"+(overTime-startTime+" ms!")); judgeSorted(arry); } catch (Exception e) { e.printStackTrace(); } } private static void judgeSorted(Comparable[] arry) { for (int i = 0; i < arry.length-1; i++) { if(arry[i].compareTo(arry[i+1])<0) { System.out.println("排序失败!"); return; } } System.out.println("排序成功!"); } public static void print(Object[] data) { int n = data.length; for(int i=0;imax; Integer[] data = new Integer[n]; for (int i = 0; i < data.length; i++) { data[i] = new Integer((int)(Math.random()*(max-min+1))+min); } return data; } }