java对数组排序进行封装Arrays.sort() 里面进行了快速排序。手动实现一下数组的简单排序
冒泡排序 插入排序 选择排序
package arrays.simples.sort;
public class SimpleSort {
/**
* 数组冒泡排序
*/
public static int[] bubbleSort(int[] arrays) {
for (int i = 0; i <= arrays.length; i++) {
boolean flag = true;
for (int j = 0; j < arrays.length - 1; j++) {
if (arrays[j] > arrays[j + 1]) {
int temp = arrays[j];
arrays[j] = arrays[j + 1];
arrays[j + 1] = temp;
flag = false;
}
}
if (flag) { // 已顺序
break;
}
System.out.print("第" + (i + 1) + "轮遍历:");
for (int value : arrays) {
System.out.print(value);
}
System.out.println();
}
return arrays;
}
/**
* 插入排序
*/
public static int[] insertSort(int[] arrays) {
int insert = 0;
for (int i = 0; i < arrays.length; i++) {
insert = arrays[i]; // 要插入的值
int j = 0;
for (j = i; j > 0 && insert <= arrays[j - 1]; j--) {
arrays[j] = arrays[j - 1];
}
arrays[j] = insert;
}
return arrays;
}
/**
* 选择排序
*/
public static int[] selectSort(int[] arrays) {
int minTemp = 0; // 存储最小值
for (int i = 0; i < arrays.length - 1; i++) {
for (int j = i + 1; j < arrays.length; j++) {
if (arrays[i] > arrays[j]) {
minTemp = arrays[j];
arrays[j] = arrays[i];
arrays[i] = minTemp;
}
}
System.out.print("第" + (i + 1) + "轮遍历:");
for (int value : arrays) {
System.out.print(value);
}
System.out.println();
}
return arrays;
}
}
测试类
package arrays;
import arrays.simples.sort.SimpleSort;
public class Test {
public static void main(String[] args) {
int[] arrays = {5, 4, 9, 6, 3, 7, 1, 8, 2};
// 冒泡排序
// arrays = SimpleSort.bubbleSort(arrays);
// 选择排序
// arrays = SimpleSort.selectSort(arrays);
// 插入排序
arrays = SimpleSort.insertSort(arrays);
for (int value : arrays) {
System.out.print(value + " ");
}
}
}