排序算法(上次更新2021.03.25)
1. 冒泡排序
private final int [] arr = new int[]{1,3,2,8,5,6,7,4};
public void bubbleSort(){
for(int i = 0; i < arr.length; i++){
for (int j = 0; j < arr.length - i - 1; j++){
if (arr[j] > arr[j+1]){
int temp = arr[j+1];
arr[j+1] = arr[j];
arr[j] = temp;
}
}
}
System.out.println("冒泡排序结果如下:");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + "");
}
}
2. 选择排序
-
代码实现:
private final int [] arr = new int[]{1,3,2,8,5,6,7,4};
public void selectSort(){
for (int i = 0; i < arr.length; i++){
int min = arr[i];
int index = i;
for (int j = i + 1; j < arr.length; j++){
if (arr[j] < min){
min = arr[j];
index = j;
}
}
int temp = arr[i];
arr[i] = min;
arr[index] = temp;
}
System.out.println();
System.out.println("选择排序结果如下:");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + "");
}
}
3. 插入排序
public void insertSort2(int[] arr) {
for (int i = 0; i < arr.length; i++) {
int insertVal = arr[i];
int insertIndex = i - 1;
while (insertIndex >= 0 && arr[insertIndex] > insertVal) {
arr[insertIndex + 1] = arr[insertIndex];
insertIndex--;
}
if (insertIndex + 1 != i) {
arr[insertIndex + 1] = insertVal;
}
}
System.out.println();
System.out.println("插入排序结果如下:");
System.out.println(Arrays.toString(arr));
}
4. 希尔排序
public void shellSort(int[] arr) {
for (int d = arr.length / 2; d > 0; d /= 2) {
for (int i = d; i < arr.length; i++) {
for (int j = i - d; j >= 0; j -= d) {
if (arr[j] > arr[j + d]) {
int temp = arr[j];
arr[j] = arr[j + d];
arr[j + d] = temp;
}
}
}
}
System.out.println();
System.out.println("希尔排序结果如下:");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + "");
}
}
5. 快速排序
-
代码实现:
public void quickSort(int[] arr, int left, int right){
int l = left;
int r = right;
int pivot = arr[(left + right) / 2];
int temp = 0;
while (l < r){
while (arr[l] < pivot){
l += 1;
}
while (arr[r] > pivot){
r -= 1;
}
if (l >= r){
break;
}
temp = arr[l];
arr[l] = arr[r];
arr[r] = temp;
if (arr[l] == pivot){
r -= 1;
}
if (arr[r] == pivot){
l += 1;
}
}
if (l == r){
l += 1;
r -= 1;
}
if (left < r){
quickSort(arr, left, r);
}
if (right > l){
quickSort(arr, l, right);
}
}
6. 归并排序
7. 时间复杂度
![image-20210324170603286](https://i-blog.csdnimg.cn/blog_migrate/05999cf1267339a833c6dc26d450a9df.png)