二分查找指定数据
对于一个有序数组,我们通常采用二分查找的方式来定位某一元素,请编写二分查找的算法,在数组中查找指定元素。
给定一个整数数组A,同时给定要查找的元素val,请返回它在数组中的位置,若不存在该元素,返回-1。
若该元素出现多次,请返回第一次出现的位置。
二分查找的前提是数组必须是有序的,下面是有序数组实现二分查找:
public class Test {
public static void main(String[] args) {
int n[] = {1,2,3,4,5,6,7,8,9};
System.out.println(getPoint(n,3));;
}
public static int getKey(int n[],int val){
int start = 0;
int end = n.length-1;
int result = -1;
while (start <= end){
int mid = start + (end - start) / 2;
if(n[mid] > val){
end = mid - 1;
}else if(n[mid] < val){
start = mid + 1;
}else{
return mid;
}
}
return result;
}
}
冒泡实现有序数组
实现对数组 n 进行排序,包含从小到大,或者从大到小两种情况。
public class A2 {
public static void main(String[] args) {
int n[] = {0,9,3,6,2,1,7,5,8,4};
System.out.println("正序:"+Arrays.toString(getAscSort(n)));
System.out.println("倒序:"+Arrays.toString(getDescSort(n)));
}
/**
* 正序
* @param n
* @return
*/
public static int[] getAscSort(int n[]){
if(n==null||n.length<=1){
return n;
}else{
for (int i = 0; i < n.length - 1; i++) {
for (int j = 0; j < n.length - i - 1; j++) {
if(n[j]>n[j+1]){
int temp = n[j];
n[j] = n[j+1];
n[j+1] = temp;
}
}
}
return n;
}
}
/**
* 倒序
* @param n
* @return
*/
public static int[] getDescSort(int n[]){
if(n==null||n.length<=1){
return n;
}else{
for (int i = 0; i < n.length - 1; i++) {
for (int j = 0; j < n.length - i - 1; j++) {
if(n[j]<n[j+1]){
int temp = n[j];
n[j] = n[j+1];
n[j+1] = temp;
}
}
}
return n;
}
}
}