冒泡排序法
private void getData(){
int[] nums = {14,9,8,25,47,95,6};
for (int i=0;i<nums.length;i++){
for (int j=i;j<nums.length;j++){
if (nums[i]>nums[j]){
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}
}
// 6,8,9,14,25,47,95
int res = searchLoop(nums,47);
Log.e("TAG","wangs數(shù)組下標(biāo)為"+res);
}
二分法查找
/**
* 循環(huán)二分查找,返回第一次出現(xiàn)該值的位置
*
* @param array
* 已排序的數(shù)組
* @param findValue
* 需要找的值
* @return 值在數(shù)組中的位置,從0開始。找不到返回-1
*/
public static int searchLoop(int[] array, int findValue) {
// 如果數(shù)組為空,直接返回-1,即查找失敗
if (array == null) {
return -1;
}
// 起始位置
int start = 0;
int count = 0;
// 結(jié)束位置
int end = array.length - 1;
while (start <= end) {
count++;
// 中間位置
int middle = (start + end) / 2;
// 中值
int middleValue = array[middle];
if (findValue == middleValue) {
// 等于中值直接返回
return middle;
} else if (findValue < middleValue) {
// 小于中值時(shí)在中值前面找
end = middle - 1;
} else {
// 大于中值在中值后面找
start = middle + 1;
}
}
// 返回-1,即查找失敗
return -1;
}