排序算法(二)——冒泡排序

排序原理

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());
		}
	}
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值