You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
android-notes/blogs/Algorithm/八大排序.md

80 lines
1.7 KiB

---
八大排序
---
#### 前言
八大排序:
1. 冒泡排序
2. 插入排序
3. 选择排序
4. 快速排序
5. 堆排序
#### 冒泡排序
```java
private static void sort(int[] data) {
//排序
for (int i = 0; i < data.length - 1; i++) {
boolean isSorted = true;
for (int j = 0; j < data.length-1-i; j++) {
if (data[j+1] < data[j]) {
int temp = data[j+1];
data[j+1] = data[j];
data[j] = temp;
isSorted = false;
}
}
if (isSorted) break;
}
//输出
for (int i = 0; i < data.length; i++) {
System.out.println(data[i]);
}
}
```
#### 插入排序
```java
private static void sort(int[] data) {
//排序
for (int i = 1; i < data.length; i++) {
for (int j = i; (j > 0) && (data[j - 1] > data[j]); j--) {
int temp = data[j];
data[j] = data[j - 1];
data[j - 1] = temp;
}
}
//输出
for (int i = 0; i < data.length; i++) {
System.out.println(data[i]);
}
}
```
#### 选择排序
```java
private static void sort(int[] data) {
//排序
for (int i = 0; i < data.length - 1; i++) {
for (int j = i + 1; j < data.length; j++) {
if (data[i] > data[j]) {
int temp = data[i];
data[i] = data[j];
data[j] = temp;
}
}
}
//输出
for (int i = 0; i < data.length; i++) {
System.out.println(data[i]);
}
}
```
#### 快速排序