//数组线性查找
String[] arr = new String[]{"JJ","DD","MM","BB","GG","AA"};
String dest = "BB";
boolean isFlag = true;
for(int i = 0;i < arr.length;i++){
if(dest.equals(arr[i])){
sout("找到了元素");
isFlag = false;
break;
}
}
if(isFlag){
sout("没找到")
}
//二分法查找
//前提所要查找的数组必须有序
int[] arr = new int[]{-12,-1,0,2,4,8,9,12,45,78,153,952};
int dest = 4;
int head = 0;//初始的首索引
int end = arr.length - 1;//初始的末索引
boolean isFlag = true;
while(head <= end){
int middle = (head + end) / 2;
if(dest == arr[middle]){
sout("找到了指定元素");
isFlag = false;
break;
}else if(arr[middle] > dest){
end = middle -1;
}else{
head = middle + 1;
}
}
//冒泡排序
int[] arr = new int[]{56,12,45,32,6545,213,45,123,45,20};
for(int i = 0;i < arr.length - 1,i++){
for(int j = 0;j < arr.length - 1 - i;j++){
if(arr[j] > arr[j + 1]){
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
//快速排序
public class QuickSort {
private static void swap(int[] data, int i, int j) {
int temp = data[i];
data[i] = data[j];
data[j] = temp;
}
private static void subSort(int[] data, int start, int end) {
if (start < end) {
int base = data[start];
int low = start;
int high = end + 1;
while (true) {
while (low < end && data[++low] - base <= 0)
;
while (high > start && data[--high] - base >= 0)
;
if (low < high) {
swap(data, low, high);
} else {
break;
}
}
swap(data, start, high);
subSort(data, start, high - 1);//递归调用
subSort(data, high + 1, end);
}
}
public static void quickSort(int[] data){
subSort(data,0,data.length-1);
}
public static void main(String[] args) {
int[] data = { 9, -16, 30, 23, -30, -49, 25, 21, 30 };
System.out.println("排序之前:\n" + java.util.Arrays.toString(data));
quickSort(data);
System.out.println("排序之后:\n" + java.util.Arrays.toString(data));
}
}