開始重新找工作了,複習一下常用算法和數據結構
- 冒泡排序
/**
* 冒泡排序
* 每趟冒出一個最大數/最小數
* 每次運行數量:總數量-運行的趟數(已冒出)
*/
public void bubbleSort() {
for (int i = 0; i < array.length - 1; i++) {
for (int j = 0; j < array.length - i - 1; j++) {
if (array[j] > array[j + 1]) {
int t = array[j];
array[j] = array[j + 1];
array[j + 1] = t;
}
}
}
}
- 選擇排序
/***
* 選擇排序
* 每趟選擇一個最大數/最小數
* 每次運行數量:總數量-運行的趟數(已選出)
*/
public void selectSort(){
for(int i = 0; i < elems-1; i++) {//排序趟數 n-1次就行了
int min = i;
for(int j = i+1; j < elems; j++){ //排序次數 每趟選擇一個數出來,-1次
if(intArray[j] < intArray[min]){
min = j;
}
}
if(i != min ){
int temp = intArray[i];
intArray[i] = intArray[min];
intArray[min] = temp;
}
display();
}
}
- 插入排序
/**
* 插入排序
* 每趟選擇一個待插入的數
* 每次運行把待插入的數放在比它大/小後面
*/
public void insertSort(int[] array) {
for (int i = 0; i < array.length; i++) {
int temp = array[i];
int j = i;
while (j > 0 && temp < array[j - 1]) {
array[j] = array[j - 1];
j--;
}
array[j] = temp;
}
}
- 快速排序
/**
* 快速排序
* 選擇一個基準數將數組利用遞歸二分,直到數組不能再分爲止;
*/
public void quickSort(int[] array, int low, int high) {// 傳入low=0,high=array.length-1;
int pivot, p_pos, i, t;// pivot->位索引;p_pos->軸值。
if (low < high) {
p_pos = low;
pivot = array[p_pos];
for (i = low + 1; i <= high; i++) {
if (array[i] < pivot) {
p_pos++;
t = array[p_pos];
array[p_pos] = array[i];
array[i] = t;
}
}
t = array[low];
array[low] = array[p_pos];
array[p_pos] = t;
// 分而治之
quickSort(array, low, p_pos - 1);// 排序左半部分
quickSort(array, p_pos + 1, high);// 排序右半部分
}
}
- 運行
public static void main(String[] args) {
int[] array = {4, 44, 7, 22, 66, 5, 3};
Algorithm2 a = new Algorithm2();
a.bubbleSort(array);
// a.selectSort(array);
// a.insertSort(array);
// a.quickSort(array, 0, array.length - 1);
a.show(array);
}
- 展示
public void show(int[] array) {
for (int v : array) {
System.out.print(v + "\t");
}
}