1、冒泡
public static void bubbleSort(int a[]) {
int temp;
boolean complete = true;
for (int i = 1; i < a.length; i++) {
complete = true;
for (int j = 0; j < a.length - i; j++) {
// 循環每次把最大的數放置在最後
if (a[j] > a[j + 1]) {
temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
complete = false;
}
print(a);
}
if (complete) { // 表示前面的數已經都是按序列了。所以後面for循環已經沒有必要再執行了,能夠直接斷開
break;
}
}
}
2、歸併
public static void merge_sort(int a[], int low, int high) {
if (low < high) {
int mid = (low + high) / 2;
merge_sort(a, low, mid);
merge_sort(a, mid + 1, high);
merge(a, low, mid, high);
}
}
public static void merge(int a[], int low, int mid, int high) {
int temp[] = new int[high - low + 1];
int k;
int left_low = low;
int left_high = mid;
int right_low = mid + 1;
int right_high = high;
for (k = 0; left_low <= left_high && right_low <= right_high; k++) {
if (a[left_low] <= a[right_low]) {
temp[k] = a[left_low++];
} else {
temp[k] = a[right_low++];
}
}
if (left_low <= left_high) {
for (int i = left_low; i <= left_high; i++) {
temp[k++] = a[i];
}
}
if (right_low <= right_high) {
for (int i = right_low; i <= right_high; i++) {
temp[k++] = a[i];
}
}
for (int i = 0; i < high - low + 1; i++) {
a[low + i] = temp[i];
}
}
3、快排
public static void quick_sort(int a[], int left, int right) {
if (left < right) {
int temp = a[left];
int i = left, j = right;
while (i < j) {
while (i < j && a[j] >= temp) {
j--;
}
if (i < j) {
a[i] = a[j];
i++;
}
while (i < j && a[i] <= temp) {
i++;
}
if (i < j) {
a[j] = a[i];
j--;
}
}
a[i] = temp;
quick_sort(a, left, i - 1);
quick_sort(a, i + 1, right);
}
}