package sort;
/**
* 排序算法(升序)
* @author Allen
* stable sort: 稳定排序
* unstable sort:
* In-place sort: 不占用额外内存或占用常数的内存
* Out-place sort:
*/
public class Sort {
public static int[] arr = { 3, 5, 2, 9, 6, 1, 4, 8, 7, 0 };
/**
* 插入排序
* 特点:stable sort、In-place sort
* 方法核心1:从左到右依次保证有序,然后将下一个元素插入到左侧适当位置
* 方法核心2:对第i个,依次,从右往左比较,若大于第i个的值,则将当前值向右移动,最后不能移动时,则将i插入到最终的位置
* 最优复杂度:当输入数组就是排好序的时候,复杂度为O(n),而快速排序在这种情况下会产生O(n^2)的复杂度。
* 最差复杂度:当输入数组为倒序时,复杂度为O(n^2)
*/
static void insertSort(int[] arr) {
for (int i = 1; i < arr.length; i++) {
int j = i - 1;
int temp = arr[i];
while (j >= 0 && arr[j] > temp) {
arr[j+1] = arr[j];
j--;
}
arr[j+1] = temp;
}
}
/**
* 冒泡排序(优化版)
* 特点:stable sort、In-place sort
* 方法核心1:i每循环一次,从最右侧依次比较相邻两个,若相同,则交换,最终将最小的数放到最左侧,下次比较则不比较最左侧的数(通过i++来实现)
* 方法核心2:首先假设数组是有序的,若产生了交换,则证明数组无序,若未产生交换,则数组为有序,可结束方法。
* 最优复杂度:O(n)
* 最差复杂度:O(n^2)
*/
public static void bubbleSort(int[] arr){
boolean isSorted;
int temp;
for (int i = 0; i < arr.length - 1; i++) {
isSorted = true;
for (int j = arr.length - 1; j > i; j--) {
if(arr[j] < arr[j-1]){
temp = arr[j];
arr[j] = arr[j-1];
arr[j-1] = temp;
isSorted = false;
}
}
if(isSorted == true){
return;
}
}
}
/**
* 选择排序
* 特点:In-place sort,unstable sort
* 方法核心:每次找一个未排序部分的最小值,并放到未排列部分的最左侧
* 最优复杂度:O(n^2)
* 最差复杂度:O(n^2)。
*/
public static void selectSort(int[] arr){
int minIndex;
int min;
for (int i = 0; i < arr.length - 1; i++) {
minIndex = i;
for (int j = i+1; j < arr.length; j++) {
if(arr[minIndex] > arr[j]){
minIndex = j;
}
}
min = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = min;
}
}
/**
* 测试方法
*/
public static void main(String[] args) {
selectSort(arr);
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i]);
if(i != arr.length -1){
System.out.print(",");
}
}
}
}
JAVA排序算法
最新推荐文章于 2026-06-20 21:44:23 发布

1609

被折叠的 条评论
为什么被折叠?



