简单排序算法-冒泡,选择,插入


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

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值