話不多說,直接看代碼,代碼都已經(jīng)經(jīng)過測(cè)試。
class Test {
/**
* @param array
*/
public static void bubbleSort(int array[]) {
int length = array.length;
int temp;
for (int i = 0; i < length; i++) {
for (int j = 0; j < length - i - 1; j++) {
if (array[j] > array[j + 1]) {
temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
}
// 快速排序
public static void quickSort(int s[], int left, int right) {
if (left < right) {// 防止左右值傳入有誤
//Swap(s[left], s[(left + right) / 2]); //將中間的這個(gè)數(shù)和第一個(gè)數(shù)交換 參見注1
int i = left;
int j = right;
int x = s[left];//s[l]即s[i]就是第一個(gè)坑
while (i < j) {
while (i < j && s[j] >= x) // 從右向左找第一個(gè)小于x的數(shù)
j--;
if (i < j) {
s[i] = s[j];// 將找到的這個(gè)數(shù)填到挖的坑里
i++;
}
while (i < j && s[i] < x) // 從左向右找第一個(gè)大于等于x的數(shù)
i++;
if (i < j) {
s[j] = s[i];
j--;
}
}
// 退出時(shí), i等于j, 將x填到這個(gè)坑中
s[i] = x;
// i指向坑的位置
quickSort(s, left, i - 1); // 遞歸調(diào)用
quickSort(s, i + 1, right);
}
}
// 插入排序
public static void insertSort(int[] a) {
int length = a.length;//數(shù)組長度
int insertNum;//要插入的數(shù)
for (int i = 1; i < length; i++) {//插入的次數(shù)
insertNum = a[i];//要插入的數(shù)
int j = i - 1;//已經(jīng)排序好的序列元素個(gè)數(shù)
while (j >= 0 && a[j] > insertNum) {//序列從后到前循環(huán),將大于insertNum的數(shù)向后移動(dòng)一格
a[j + 1] = a[j];//元素移動(dòng)一格
j--;
}
a[j + 1] = insertNum;//將需要插入的數(shù)放在要插入的位置
}
}
public static void selectSort(int[] a) {
int length = a.length;
for (int i = 0; i < length; i++) {//循環(huán)次數(shù)
int key = a[i];
int position=i;
for (int j = i + 1; j < length; j++) {//選出最小的值和位置
if (a[j] < key) {
key = a[j];
position = j;
}
}
a[position]=a[i];//交換位置
a[i]=key;
}
}
public static void printArray(@NotNull int array[]) {
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
}
public static void main(String[] args) {
int array[] = {3, 1, 4, 6, 8, 2, 9, 0};
// bubbleSort(array);
selectSort(array);
printArray(array);
}
}
參考文章