一、冒泡排序
public class Bubble {
//对数组a中的元素进行排序
public static void sort(Comparable[] a){
for(int i=a.length-1;i>0;i--){
for(int j=0;j0;
}
//数组元素i和j交换位置
private static void exch(Comparable[] a,int i,int j){
Comparable temp;
temp = a[i];
a[i]=a[j];
a[j]=temp;
}
}
冒泡排序测试类
public class BubbleTest {
public static void main(String[] args) {
Integer[] arr = {4,5,6,3,2,1};
Bubble.sort(arr);
System.out.println(Arrays.toString(arr));//{1,2,3,4,5,6}
}
}
二、选择排序
public class Selection {
//对数组a中的元素进行排序
public static void sort(Comparable[] a){
for(int i=0;i<=a.length-2;i++){
//定义一个变量,记录最小元素所在的索引,默认为参与选择排序的第一个元素所在的位置
int minIndex = i;
for(int j=i+1;j0;
}
//数组元素i和j交换位置
private static void exch(Comparable[] a,int i,int j){
Comparable temp;
temp = a[i];
a[i]=a[j];
a[j]=temp;
}
}
选择排序测试类
public class SelectionTest {
public static void main(String[] args) {
//原始数据
Integer[] a = {4,6,8,7,9,2,10,1};
Selection.sort(a);
System.out.println(Arrays.toString(a));//{1,2,4,5,7,8,9,10}
}
}
三、插入排序
public class Insertion {
//对数组a中的元素进行排序
public static void sort(Comparable[] a) {
for (int i = 1; i < a.length; i++) {
for (int j = i; j > 0; j--) {
//比较索引j处的值和索引j-1处的值,如果索引j-1处的值比索引j处的值大,则交换数据,如果不大,那么就找到合适的位置了,退出循环即可;
if (greater(a[j - 1], a[j])) {
exch(a, j - 1, j);
} else {
break;
}
}
}
}
//比较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;
}
}
插入排序测试类
public class InsertionTest {
public static void main(String[] args) {
Integer[] a = {4,3,2,10,12,1,5,6};
Insertion.sort(a);
System.out.println(Arrays.toString(a));//{1,2,3,4,5,6,10,12}
}
}



