public class ArraySort {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int a[] = { 100, 3, 0, 4, 5, 7, 23, 22, 33, 35, 76, 3, 32, 32, 98 };
System.out.println("目标数组为:");
print(a);
System.out.println("冒泡排序后的数组为:");
print(bubbleSort(a));
System.out.println("选择排序后的数组为:");
print(selectSort(a));
System.out.println("插入排序后的数组为:");
print(insertSort(a));
System.out.println("快速排序之后的数组为:");
print(quickSort(a, 0, a.length-1));
}
// 冒泡排序
public static int[] bubbleSort(int data[]) {
for (int i = 0; i < data.length; i++) {
int temp = 0;
for (int j = 0; j < data.length - i - 1; j++) {
if (data[j] > data[j + 1]) {
temp = data[j];
data[j] = data[j + 1];
data[j + 1] = temp;
}
}
}
return data;
}
// 选择排序
public static int[] selectSort(int data[]) {
for (int i = 0; i < data.length; i++) {
int index = 0;
int temp;
for (int j = 1; j < data.length - i; j++) {
if (data[index] < data[j]) {
index = j;
}
}
temp = data[index];
data[index] = data[data.length - 1 - i];
data[data.length - 1 - i] = temp;
}
return data;
}
// 插入排序
public static int[] insertSort(int data[]) {
for (int i = 1; i < data.length; i++) {
int temp = 0;
for (int j = 0; j < i; j++) {
if (data[i] < data[j]) {
temp = data[i];
data[i] = data[j];
data[j] = temp;
}
}
}
return data;
}
// 快速排序
public static int[] quickSort(int data[], int from, int to) {
int p;
if (from < to) {
p = position(data, from, to);
quickSort(data, from, p - 1);
quickSort(data, p + 1, to);
}
return data;
}
//求data[from]这个元素在排好序之后的数组里面的位置,并将该位置的值附为data[from]
public static int position(int data[], int from, int to) {
int i = from;
int j = to;
int temp = data[i];
while (i < j) {
while (i < j && data[j] > temp) {
j--;
}
if (i < j) {
data[i] = data[j];
i++;
}
while (i < j && data[i] < temp) {
i++;
}
if (i < j) {
data[j] = data[i];
j--;
}
}
data[i] = temp;
return i;
}
// 打印数组
public static void print(int[] data) {
for (int i = 0; i < data.length; i++) {
System.out.print(data[i] + " ");
}
System.out.println();
}
}
运行结果:
目标数组为:
100 3 0 4 5 7 23 22 33 35 76 3 32 32 98
冒泡排序后的数组为:
0 3 3 4 5 7 22 23 32 32 33 35 76 98 100
选择排序后的数组为:
0 3 3 4 5 7 22 23 32 32 33 35 76 98 100
插入排序后的数组为:
0 3 3 4 5 7 22 23 32 32 33 35 76 98 100
快速排序之后的数组为:
0 3 3 4 5 7 22 23 32 32 33 35 76 98 100