一、冒泡排序
定义:相邻的两个值比较, 然后交换位置, 每次循环都会将有效元素中最大的或最小的移动到有效位的最后经过多次循环之后,就可以排出一个有序的数组。
import java.util.Arrays;
public class BubbleSort {
public static void main(String[] args) {
int[] arr = { 98, 78, 56, 78, 45, 23, 56, 78, 65, 54, 76, 25, 85, 23, 4, 65, 22, 1 };
int[] result = bubbleSore(arr);
System.out.println(Arrays.toString(result));
}
public static int[] bubbleSore(int[] arr) {
//外层循环控制循环次数
for (int i = 0; i < arr.length ; i++) {
//内层循环将相邻元素进行比较,每次比较会确定一个元素的位置,所以长度要减i
for (int j = 0; j < arr.length - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
return arr;
}
}
打印结果:
二、选择排序
选择排序(Selection sort)是一种简单直观的排序算法。它的工作原理是每一次从待排序的数据元素中选出最小(或最大)的一个元素,存放在序列的起始位置,然后,再从剩余未排序元素中继续寻找最小(大)元素,然后放到已排序序列的末尾。以此类推,直到全部待排序的数据元素排完。 选择排序是不稳定的排序方法。
代码实现:
public static int[] selectSort(int[] a) {
for (int i = 0; i < a.length - 1; i++) {
int minIndex = i; // 无序区的最小数据数组下标
for (int j = i + 1; j < a.length; j++) {
// 在无序区中找到最小数据并保存其数组下标
if (a[j] < a[minIndex]) {
minIndex = j;
}
}
// 将最小元素放到本次循环的前端
int temp = a[i];
a[i] = a[minIndex];
a[minIndex] = temp;
}
return a;
}