package com.cjy.concurrent;
public class Sort {
// 插入排序
public static void insertSort(int[] array) {
int[] result = new int[array.length + 1];
if (array != null && array.length > 0) {
result[0] = array[0];
}
for (int i = 1; i < array.length; i++) {
int flag = -1;
// 查找插入位置
for (int j = 0; j < result.length; j++) {
if (array[i] < result[j]) {
flag = j;
break;
}
}
if (flag == -1) {
// 没有找到直接放到位置i
result[i] = array[i];
} else {
// 找到插入位置,移动元素
for (int k = result.length - 1; k > flag; k--) {
result[k] = result[k - 1];
}
result[flag] = array[i];
}
}
// 打印输出
for (int m = 0; m < result.length - 1; m++) {
System.out.print(result[m] + " ");
}
System.out.print("\n");
}
// 冒泡排序
public static void bubbleSort(int[] array) {
int length = array.length;
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < length - 1; j++) {
if (array[j] > array[j + 1]) {
int flag = array[j + 1];
array[j + 1] = array[j];
array[j] = flag;
}
}
length--;
}
// 打印输出
for (int m = 0; m < array.length; m++) {
System.out.print(array[m] + " ");
}
System.out.print("\n");
}
// 快速排序
public static void quickSort(int[] array, int begin, int end) {
if (begin < end) {
int p = position(array, begin, end);
quickSort(array, begin, p - 1);
quickSort(array, p + 1, end);
}
}
public static int position(int[] array, int begin, int end) {
int flag = array[begin];
int i = begin, j = end;
while (i < j) {
while (j > i && array[j] > flag) {
j--;
}
array[i] = array[j];
while (i < end && array[i] < flag) {
i++;
}
array[j] = array[i];
}
array[i] = flag;
return i;
}
public static void main(String[] args) {
int[] array1 = { 2, 4, 9, 3, 6, 7, 1, 5 };
int[] array2 = array1;
int[] array3 = array1;
insertSort(array1);
bubbleSort(array2);
quickSort(array3, 0, 7);
//打印输出
for (int m = 0; m < array3.length; m++) {
System.out.print(array3[m] + " ");
}
}
}
测试结果:
1 2 3 4 5 6 7 9
1 2 3 4 5 6 7 9
1 2 3 4 5 6 7 9