1、冒泡排序
public static void bubbleSort(int[] a) {
int length= a.length;
for (int i= 0; i< length; i++) {
boolean hasChange= false;
for (int j= 0; j< length- 1 - i; j++) {
if (a[j] > a[j+ 1]) {
int temp= a[j];
a[j] = a[j+ 1];
a[j+ 1] = temp;
hasChange= true;
}
}
if (!hasChange) {
break;
}
}
}
2、插入排序
public static void insertionSort(int[] a) {
int length= a.length;
for (int i= 1; i< length; i++) {
int previous= a[i];
int j= i- 1;
for (; j>= 0; j--) {
if (a[j] > previous) {
a[j+ 1] = a[j];
} else {
break;
}
}
a[j+ 1] = previous;
}
}
3、快速排序
public static void main(String[] args) {
int[] a= new int[]{6, 5, 4, 7, 8, 9, 1, 2, 3};
int length= a.length;
quickSort(a, 0, length- 1);
for (int i: a) {
System.out.println(i);
}
}
public static void quickSort(int[] a, int start, int end) {
if (start>= end) {
return;
}
int partition= partition(a, start, end);
quickSort(a, start, partition- 1);
quickSort(a, partition+ 1, end);
}
public static int partition(int[] a, int start, int end) {
int pivot= a[end];
int i= start;
for (int j= start; j< end; j++) {
if (a[j] < pivot) {
if (i!= j) {
swap(a, i, j);
}
i++;
}
}
swap(a, i, end);
return i;
}
public static void swap(int[] a, int i, int j) {
int temp= a[i];
a[i] = a[j];
a[j] = temp;
}