1、快速排序
public void sort(int[] a,int low,int high){
int start = low;
int end = high;
int key = a[low];
while(end>start){
//從后往前比較
while(end>start&&a[end]>=key) //如果沒(méi)有比關(guān)鍵值小的,比較下一個(gè),直到有比關(guān)鍵值小的交換位置,然后又從前往后比較
end--;
if(a[end]<=key){
int temp = a[end];
a[end] = a[start];
a[start] = temp;
}
//從前往后比較
while(end>start&&a[start]<=key)//如果沒(méi)有比關(guān)鍵值大的,比較下一個(gè),直到有比關(guān)鍵值大的交換位置
start++;
if(a[start]>=key){
int temp = a[start];
a[start] = a[end];
a[end] = temp;
}
//此時(shí)第一次循環(huán)比較結(jié)束,關(guān)鍵值的位置已經(jīng)確定了。左邊的值都比關(guān)鍵值小,右邊的值都比關(guān)鍵值大,但是兩邊的順序還有可能是不一樣的,進(jìn)行下面的遞歸調(diào)用
}
//遞歸
if(start>low) sort(a,low,start-1);//左邊序列。第一個(gè)索引位置到關(guān)鍵值索引-1
if(end<high) sort(a,end+1,high);//右邊序列。從關(guān)鍵值索引+1到最后一個(gè)
}
}
2、冒泡
public void bubbleSort(int []a){
int len=a.length;
for(int i=0;i<len;i++){
for(int j=0;j<len-i-1;j++){//注意第二重循環(huán)的條件
if(a[j]>a[j+1]){
int temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
}
3、二分法
public static int search(int[] arr, int key) {
int start = 0;
int end = arr.length - 1;
while (start <= end) {
int middle = (start + end) / 2;
if (key < arr[middle]) {
end = middle - 1;
} else if (key > arr[middle]) {
start = middle + 1;
} else {
return middle;
}
}
return -1;
}
4、單例模式
// 線(xiàn)程安全的懶漢式單例
public class Singleton3 {
//使用volatile關(guān)鍵字防止重排序,因?yàn)?new Instance()是一個(gè)非原子操作,可能創(chuàng)建一個(gè)不完整的實(shí)例
private static volatile Singleton3 singleton3;
private Singleton3() {
}
public static Singleton3 getSingleton3() {
// Double-Check idiom
if (singleton3 == null) {
synchronized (Singleton3.class) { // 1
// 只需在第一次創(chuàng)建實(shí)例時(shí)才同步
if (singleton3 == null) { // 2
singleton3 = new Singleton3(); // 3
}
}
}
return singleton3;
}
}