一、冒泡排序
代码如下(示例):
public class BubbleSort {
public static void main(String args[]) {
//排序前的数组
int[] arr = {1, 4, 7, 2, 5, 8, 3, 6, 9};
//总共需要对比多少趟
for (int i = 0; i < arr.length - 1; i++) {
//每一趟需要对比的次数
for (int j = 0; j < arr.length - 1 - i; j++) {
int temp;
//判断是否需要进行数据交换
if (arr[j] > arr[j + 1]) {
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
//遍历排序后的数组
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + ",");
}
}
}
输出结果:1,2,3,4,5,6,7,8,9,
二、选择排序
代码如下(示例):
public class SelectionSort {
public static void main(String[] args) {
int[] arr = {1, 4, 7, 2, 5, 8, 3, 6, 9};
//总共需要对比多少趟
for (int i = 0; i < arr.length - 1; i++) {
//定义标杆k初始值为i
int k = i;
//每一趟需要对比的次数
for (int j = k + 1; j < arr.length; j++) {
//记录值小的位置
if (arr[j] < arr[k]) {
k = j;
}
}
//如果最小值不是在i那个位置,就数据交换
if (i != k) {
int temp = arr[i];
arr[i] = arr[k];
arr[k] = temp;
}
}
//增强for循环遍历选择排序后数组
for (int num : arr) {
System.out.print(num + " ");
}
}
}
输出结果:1 2 3 4 5 6 7 8 9
三、插入排序
代码如下(示例):
public class InsertSort {
public static void main(String[] args) {
int[] arr = {1, 4, 7, 2, 5, 8, 3, 6, 9};
//要插入的数
int insertNum;
//因为第一次不用,所以从1开始
for (int i = 1; i < arr.length; i++) {
insertNum = arr[i];
//需要对比的元素个数
int j = i - 1;
//从后往前循环,将大于insertNum的数向后移动
while (j >= 0 && arr[j] > insertNum) {
//元素向后移动
arr[j + 1] = arr[j];
j--;
}
//找到位置,插入当前元素
arr[j + 1] = insertNum;
}
//增强for循环遍历选择排序后数组
for (int num : arr) {
System.out.print(num + " ");
}
}
}
输出结果:1 2 3 4 5 6 7 8 9