排序原理
1.比较相邻的元素,如果前一个元素比后一个元素大,就交换着两个元素的位置。
2.对每一对相邻元素做同样的工作,从开始第一对元素到结尾的最后一对元素,最终最后位置的元素就是最大值。
具体过程演示
冒泡排序具体实现
冒泡排序API设计
package sort;
//冒泡排序API
public class Bubble {
/*
* 对数组a中的元素进行排序
*/
public static void sort(Comparable[] a) {
for(int i=a.length-1;i>0;i--) {
for(int j=0;j<i;j++) {
if(greater(a[j],a[j+1])) {
exch(a,j,j+1);
}
}
}
}
/*
* 比较v元素是否大于w元素
*/
private static boolean greater(Comparable v,Comparable w) {
return v.compareTo(w)>0;
}
/*
* 数组元素i和j交换位置
*/
private static void exch(Comparable[] a,int i,int j) {
Comparable temp;
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
package test;
import java.util.Arrays;
import sort.Bubble;
public class BubbleTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
Integer[] arr = {4,5,6,3,2,1};
Bubble.sort(arr);
System.out.println(Arrays.toString(arr));
}
}
之所以这样编写是因为,在实际比较中,我们比较的不只是数值,还有对象。这样编写就可以对对象数组进行排序,只需要让对象实现Comparable接口,重写compareTo方法即可。
接下来是有关上述思想的一个练习
描述
编写学生类,学生包含姓名和年龄两个属性。对学生按照年龄进行排序。
结构如下
package student;
public class Student implements Comparable<Student>{
String name;
int age;
public Student(String s,int a){
name = s;
age = a;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + "]";
}
@Override
public int compareTo(Student o) {
// TODO Auto-generated method stub
return this.age - o.age;
}
}
package student;
public class Sort {
public static void sort(Comparable[] a) {
for(int i=a.length-1;i>0;i--) {
for(int j=0;j<i;j++) {
if(greater(a[j],a[j+1])>0) {
exchange(a,j,j+1);
}
}
}
}
public static void exchange(Comparable[] a,int i,int j) {
Comparable temp;
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
public static int greater(Comparable a,Comparable b) {
return a.compareTo(b);
}
}
package studentTest;
import student.Sort;
import student.Student;
public class StudentTest {
public static void main(String[] args) {
Student s1 = new Student("小明",19);
Student s2 = new Student("小李",34);
Student s3 = new Student("小时",2);
Student s4 = new Student("小花",36);
Student s5 = new Student("小草",21);
Student s6 = new Student("小傲",12);
Student[] s = {s1,s2,s3,s4,s5,s6};
Sort.sort(s);
for(int i=0;i<s.length;i++) {
System.out.println(s[i].toString());
}
}
}