一、int型数组冒泡排序
public static int[] bubbleSortIntNum(int[] intArr) {
if(intArr == null || intArr.length == 0) {
return intArr;
} else {
for (int i = intArr.length-1 ; i >= 0 ; i--) {
for(int j = 0; j < i ; j++) {
if(intArr[j] > intArr[j+1]) {
intArr[j] ^= intArr[j+1];
intArr[j+1] ^= intArr[j];
intArr[j] ^= intArr[j+1];
}
}
}
}
System.out.println(Arrays.toString(intArr));
return intArr;
}
二、double型数组冒泡排序
public static double[] bubbleSortDoubleNum(double[] doubleArr) {
if(doubleArr == null || doubleArr.length == 0) {
return doubleArr;
} else {
for (int i = doubleArr.length-1 ; i >= 0 ; i--) {
for(int j = 0; j < i ; j++) {
if(doubleArr[j] > doubleArr[j+1]) {
doubleArr[j] = doubleArr[j] - doubleArr[j+1];
doubleArr[j+1] = doubleArr[j] + doubleArr[j+1];
doubleArr[j] = doubleArr[j+1] - doubleArr[j];
}
}
}
}
System.out.println(Arrays.toString(doubleArr));
return doubleArr;
}
三、对象排序
1.首先对象实现Comparable接口
class Student implements Comparable<Student>{
private int num;
private String name;
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Student(int num, String name) {
this.num = num;
this.name = name;
}
public int compareTo(Student student) {
if(student == null) {
return 1;
}
if(this.num > student.getNum()) {
return 1;
} else if(this.num == student.getNum()){
return 0;
} else {
return -1;
}
}
}
2.泛型对象数组冒泡排序
public static <T> Comparable<T>[] bubbleSortObject(Comparable<T>[] objectArr) {
if(objectArr == null || objectArr.length == 0) {
return objectArr;
} else {
Comparable<T> object = null;
for (int i = objectArr.length-1 ; i >= 0 ; i--) {
for(int j = 0; j < i ; j++) {
if(objectArr[j].compareTo((T) objectArr[j+1]) > 0) {
object = objectArr[j];
objectArr[j] = objectArr[j+1];
objectArr[j+1] = object;
}
}
}
}
return objectArr;
}
3.main函数具体实现
Student[] studentArr = (Student[]) bubbleSortObject(new Student[] {new Student(17,"张三"),
new Student(16,"李四"), new Student(15,"王五"), new Student(14,"赵六"),null});
for(int i = 0 ; i < studentArr.length ; i++) {
System.out.print ((studentArr[i] == null ? null:studentArr[i].getName()) +" ");
}