冒泡排序、选择排序、插入排序
class ArrayUtils{
public static void swap(int[] a, int i, int j){
int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
//【冒泡排序】[a[l], a[r]]闭区间
public static void bubbleSort(int[] a, int l, int r){
int tmp;
boolean flag;//优化
for(int i = r - l; i >= 1; i--){
flag = false;
for(int j = l; j < l + i; j++){
if(a[j] > a[j+1]){
swap(a, j, j+1);
flag = true;
}
}
if(!flag){
break;
}
}
}
//选择排序
public static void selectSort(int[] a, int l, int r){
int tmp;
int i, j;
for(i = l; i <= r-1; i++){
tmp = i;
for(j = i + 1; j <= r; j++){
if(a[j] < a[tmp]){
tmp = j;
}
}
if(i != tmp){
swap(a, i, tmp);
}
}
}
//插入排序
public static void insertSort(int[] a, int l ,int r){
int i, j, tmp;
for(i = l; i <= r - 1; i++){
if(a[i] > a[i+1]){
tmp = a[i+1];
for(j = i; j >= l && tmp < a[j]; j--){
a[j+1] = a[j];
}
a[j+1] = tmp;
}
}
}
//打印数组
public static void print(int[] a){
for(int i = 0; i < a.length; i++){
System.out.print(a[i] + " ");
}
System.out.println();
}
}
public class Main{
//测试
public static void main(String[] args){
//测试冒泡排序
int[] a = {6,3,4,9,1,2};
ArrayUtils.print(a);
ArrayUtils.bubbleSort(a, 1, 4);
ArrayUtils.print(a);
System.out.println();
//测试选择排序
int[] b= {6,3,4,9,1,2};
ArrayUtils.print(b);
ArrayUtils.selectSort(b, 1, 4);
ArrayUtils.print(b);
System.out.println();
//测试插入排序
int[] c= {6,3,4,9,1,2};
ArrayUtils.print(c);
ArrayUtils.insertSort(c, 1, 4);
ArrayUtils.print(c);
System.out.println();
}
}
Arrays工具类排序
import java.util.Arrays;
public class Main{
public static void print(int[] a){
for(int i = 0; i < a.length; i++){
System.out.print(a[i]+" ");
}
System.out.println();
}
//测试
public static void main(String[] args){
int[] a = {6,3,4,9,1,2};
print(a);
Arrays.sort(a, 1, 5);//Arrays工具类对数组排序,左闭右开区间
print(a);
System.out.println(Arrays.binarySearch(a, 1, 5, 9));//二分查找
}
}
对象排序(借助Arrays)
查看API知道,要用Arrays对数组对象排序,得传入Comparator的实现类,实现compare方法。可以自己定义一个Comparator的实现类,也可以直接用其匿名内部类。
import java.util.Comparator;
import java.util.Arrays;
//自定义一个Comparator的实现类,自定义比较器
class MyComparator implements Comparator<Student>{
public int compare(Student s1, Student s2){
return s1.getScore() - s2.getScore();
}
}
class Student{
private String id;
private int score;
public Student(String id, int score){
this.id = id;
this.score = score;
}
public int getScore(){
return this.score;
}
public void print(){
System.out.println(this.id+" "+this.score);
}
}
public class Main{
public static void printStudents(Student[] students){
for(Student student : students){
student.print();
}
System.out.println();
}
//测试
public static void main(String[] args){
Student[] students = new Student[6];
students[0] = new Student("001", 87);
students[1] = new Student("002", 98);
students[2] = new Student("003", 88);
students[3] = new Student("004", 76);
students[4] = new Student("005", 80);
students[5] = new Student("006", 100);
printStudents(students);
Arrays.sort(students, 1, 5, new MyComparator());
printStudents(students);
}
}