package test;
public class SimpleSort {
public static void main(String[] args) {
int[] intArray = { 12, 2, 5, 6, 4, 2, 9 };// length=7
display("原数组", intArray);
bubble(intArray);
select(intArray);
insert(intArray);
}
public static void display(String name, int[] intArray) {
System.out.print(name + ": ");
for (int i : intArray) {
System.out.print(i + ",");
}
System.out.print("\n");
}
// 冒泡排序
public static void bubble(int[] ia) {
int[] intArray = ia.clone();
int length = intArray.length;
int temp;
// 迭代起泡
for (int j = 0; j < length; j++) {
// 一次起泡过程
for (int i = 0; i < length - j - 1; i++) { // 第(j+1)次起泡,不需再与最后的j个比较了,它们已经被排好序了
if (intArray[i] > intArray[i + 1]) {// 对比相邻2个的值,判断交换否
temp = intArray[i + 1];
intArray[i + 1] = intArray[i];
intArray[i] = temp;
}
}
}
display("冒泡排序", intArray);
}
// 选择排序
public static void select(int[] ia) {
int[] intArray = ia.clone();
int length = intArray.length;
int temp = intArray[0];
// 迭代每个位置的选择过程,最后位不需要了, 整个数列都排序好了
for (int i = 0; i < length - 1; i++) {
// 一次选择过程
for (int j = i + 1; j < length; j++) {// 从每个位置开始的后面的所有元素,都进行一次比较,
// 把最小的元素方到该位置上
if (intArray[j] < intArray[i]) {
temp = intArray[i];
intArray[i] = intArray[j];
intArray[j] = temp;
}
}
}
display("选择排序", intArray);
}
// 插入排序
public static void insert(int[] intArray) {
int[] ia = intArray.clone();
int length = ia.length;
int temp, j;
// 迭代插入过程, 从左边第二个位置开始,第一个默认当作最小值
for (int i = 1; i < length; i++) {
// 一次插入过程, 把当前位置的值保存到临时变量里
temp = ia[i];
// 迭代当前位置左边的元素,把比当前元素大的值都往右边移动一格
j = i;
while (j > 0 && ia[j - 1] > temp) {
ia[j] = ia[j - 1];
j--;
}
// 比它大的都往右边移动一格了,把当前位置的值插入到空档中
ia[j] = temp;
}
display("插入排序", ia);
}
}
简单排序算法-冒泡,选择,插入
最新推荐文章于 2024-10-03 13:36:06 发布