1.冒泡排序:
public void bubbleSort() {
int i, j;
for (i = 0; i < a.length - 1; i++) {
for (j = a.length - 1; j > i; j--) {
if (a[j] < a[j - 1]) {
temp = a[j - 1];
a[j - 1] = a[j];
a[j] = temp;
}
}
}
}
冒泡排序改进:
public void bubbleSort3() {
int i,j;
int exchange= 0; //标记是否交换
for (i = 0; i < a.length - 1; i++) {
exchange = 0;
for (j = a.length - 1; j > i; j--) {
if (a[j] < a[j - 1]) {
temp = a[j - 1];
a[j - 1] = a[j];
a[j] = temp;
exchange = 1; //标记交换
}
}
if(exchange != 1) {
break;
}
}
}
2.直接插入排序:
public void directSort() {
int i, j;
for (i = 1; i < a.length; i++) {
if (a[i] < a[i - 1]) {
temp = a[i];
for (j = i - 1; j >= 0 && a[j] > temp; j--) {
a[j + 1] = a[j];
}
a[j + 1] = temp;
}
}
for (i = 0; i < a.length; i++) {
System.out.println(a[i]);
}
}
3.希尔排序:
基本思想:先将整个待排序记录序列按增量d分割成若干个子序列分别进行直接插入排序,然后再用一个较小的增量d进行再次排序,以当增量减至1时,整个序列中的记录已"基本有序"时,再对全体记录进行一次直接插入排序.
public void shellSort() {
int count = 0;
int j;
for (int d = n / 2; d > 0; d /= 2) {
for (int i = d; i < n; i++) {
temp = a[i];
for (j = i - d; (j >= 0 && temp < a[j]); j = j - d) {
a[j + d] = a[j];
}
a[j + d] = temp;
}
count++;
System.out.print("第" + count + "次排序结果:");
for (int i = 0; i < n; i++) {
System.out.print(a[i] + "");
}
System.out.println();
}
}
5.快速排序
// 快速排序
public void quickSort(int[] a, int lo, int hi) {
if (lo < hi) {
int k = partition(a, lo, hi);
quickSort(a, lo, k - 1);
quickSort(a, k + 1, hi);
}
for (int i = 0; i < n; i++) {
System.out.print(a[i]);
}
System.out.println();
}
private int partition(int[] a, int lo, int hi) {
int i = lo - 1;
int key = a[hi];// 取最后一个元素做为关键值
int temp;
for (int j = lo; j < hi; j++) {
if (a[j] <= key) {
i++;
temp = a[j];
a[j] = a[i];
a[i] = temp;
}
}
a[hi] = a[i + 1];
a[i + 1] = key;
return i + 1;
}
public void quickSort2(int[] a, int lo, int hi) {
if (lo < hi) {
int k = partition2(a, lo, hi);
quickSort2(a, lo, k - 1);
quickSort2(a, k + 1, hi);
}
}
private int partition2(int[] a, int lo, int hi) {
int key = a[hi]; // 取最后一个元素
while (lo < hi) {
while (lo < hi && a[lo] <= key) {
lo++;
}
if (lo < hi) {
a[hi--] = a[lo];
}
while (lo < hi && a[hi] >= key) {
hi--;
}
if (lo < hi) {
a[lo++] = a[hi];
}
}
a[hi] = key;
return hi;
}