- 冒泡排序
对当前还未排好序的全部数,自上而下对相邻的两个数依次进行比较和调整,让较大的数往下沉,较小的往上冒。
package javastudy.sort;
public class BumbleSort {
public static void main(String[] args) {
int arr[] = new int[]{33, 22, 40, 10, 8, 15, 9, 18, 20, 1};
int n = arr.length;
int temp = -1;
for(int i = 0; i < n-1; i++) {
for(int j = 0; j < n - i - 1; j++) {
if(arr[j] > arr[j+1]){
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
for(int i = 0; i < n; i++)
System.out.println(arr[i]);
}
}
改进:若发现当前循环中没有任何数据的交换,则说明当前序列一排好序,那么可以结束循环。
package javastudy.sort;
public class BumbleSort {
public static void main(String[] args) {
int arr[] = new int[]{33, 22, 40, 10, 8, 15, 9, 18, 20, 1};
int n = arr.length;
int temp = -1;
for(int i = 0; i < n-1; i++) {
boolean tag = false;
for(int j = 0; j < n - 1 - i; j++) {
if(arr[i] > arr[j]){
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
tag = true;
}
}
if(tag) break;
}
for(int i = 0; i < n; i++)
System.out.println(arr[i]);
}
}
- 选择排序
package javastudy.sort;
public class SelectionSort {
public static void main(String[] args) {
int arr[] = new int[]{33, 22, 40, 10, 8, 15, 9, 18, 20, 1};
int n = arr.length;
int select = -1;
int temp = -1;
for(int i = 0; i < n - 1; i++) {
select = i; //记录最小值得下标
for(int j = i + 1; j < n; j++) {
if(arr[select] > arr[j]) {
select = j;
}
}
if(select != i) {
temp = arr[i];
arr[i] = arr[select];
arr[select] = temp;
}
}
for(int i = 0; i < n; i++)
System.out.println(arr[i]);
}
}
- 二元选择排序
package javastudy.sort;
public class BinarySelectSort {
public static void main(String[] args) {
int arr[] = new int[]{33, 22, 40, 10, 8, 15, 9, 18, 20, 1};
int n = arr.length;
int min, max, temp;
for(int i = 0; i <= n/2; i++) {
min = max = i;
for(int j = i + 1; j < n - i; j++) {
if(arr[min] > arr[j]) {
min = j;
continue;
}
if(arr[max] < arr[j])
max = j;
}
if(i != min) {
temp = arr[i]; arr[i] = arr[min]; arr[min] = temp;
}
if(i != max) {
temp = arr[n - i - 1];arr[n - i -1] = arr[max];arr[max] = temp;
}
}
for(int i = 0; i < n; i++) {
System.out.println(arr[i]);
}
}
}
- 插入排序
package javastudy.sort;
public class InsertSort {
public static void main(String[] args) {
int arr[] = new int[]{33, 22, 40, 10, 8, 15, 9, 18, 20, 1};
int n = arr.length;
for (int i = 1; i < n; i++) {
if (arr[i] < arr[i - 1]) {
int valueToInsert = arr[i];
int j;
for (j = i - 1; j >= 0 && valueToInsert < arr[j]; j--) {
arr[j + 1] = arr[j];
}
arr[j+1] = valueToInsert;
}
}
for(int i = 0; i < n; i++)
System.out.println(arr[i]);
}
}
- 快速排序
- 归并排序
- 桶排序/基数排序(Radix Sort)