常用排序算法
2021-01-30 14:16
标签:ret 方法 stat start 冒泡排序 out void 排序 DPoS public class Sort { //冒泡排序方法2 //选择排序 //插入排序 //优化:折半插入排序 利用二分查找 //快速排序 //二分查找 //二分查找递归 public static void main(String[] args) { 常用排序算法 标签:ret 方法 stat start 冒泡排序 out void 排序 DPoS 原文地址:https://www.cnblogs.com/coderxiaobai/p/12820331.html
//冒泡排序方法1
public static void bubbleSort1(int[] arr) {
for (int i = 0; i for (int j = 0; j if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
for (int num : arr) {
System.out.print(num + " ");
}
}
public static void bubbleSort2(int[] arr) {
for (int i = arr.length - 1; i > 0; i--) {
for (int j = 0; j if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
for (int num : arr) {
System.out.print(num + " ");
}
}
public static void selectSort(int[] arr) {
for (int i = 0; i int min = i;
for (int j = i + 1; j if (arr[min] > arr[j]) {
min = j;
}
}
if (i != min) {
int temp = arr[i];
arr[i] = arr[min];
arr[min] = temp;
}
}
for (int num : arr) {
System.out.print(num + " ");
}
}
public static void insertSort(int[] arr) {
for (int i = 0; i for (int j = i + 1; j > 0 && arr[j] int temp = arr[j];
arr[j] = arr[j - 1];
arr[j - 1] = temp;
}
}
for (int i : arr) {
System.out.print(i + " ");
}
}
public static void binaryInsertSort(int[] arr) {
for (int i = 1; i int end = i - 1;
int start = 0;
//查询要插入位置
while (start int midPos = (start + end) / 2;
if (arr[i] end = midPos - 1;
} else {
start = midPos + 1;
}
}
//暂存要插入值
int temp = arr[i];
//插入位置后元素后移
for (int j = i; j > start; j--) {
arr[j] = arr[j - 1];
}
//更新插入值
arr[start] = temp;
}
for (int i : arr) {
System.out.print(i + " ");
}
}
private static int[] quickSort(int[] arr, int low, int high) {
int start = low;
int end = high;
int item = arr[start];
while (start while (start item) {
end--;
}
while (start start++;
}
if (start start++;
} else {
int temp = arr[end];
arr[end] = arr[start];
arr[start] = temp;
}
}
if (start + 1 quickSort(arr, start + 1, high);
}
if (start - 1 > low) {
quickSort(arr, low, start - 1);
}
return arr;
}
public static void binarySearch(int num, int[] arr) {
int startPos = 0;
int endPos = arr.length - 1;
while (startPos int item = (startPos + endPos) / 2;
if (arr[item] == num) {
System.out.println("索引为:" + item);
return;
} else if (num endPos = item - 1;
} else if (num > arr[item]) {
startPos = item + 1;
}
}
System.out.println("值不存在!");
}
public static int binarySearch2(int target, int[] arr, int low, int high) {
int num = (low + high) / 2;
if (low > high) {
return -1;
}
if (arr[num] == target) {
return num;
} else if (arr[num] return binarySearch2(target, arr, num + 1, high);
} else {
return binarySearch2(target, arr, low, num - 1);
}
}
int[] arr = {3,4,2,5,6,7,3};
//bubbleSort1(arr);
//bubbleSort2(arr);
//selectSort(arr);
//insertSort(arr);
binaryInsertSort(arr);
//bina(arr);
//binarySearch(9, arr);
//insertSort(arr);
}
}