String[] arr = new String[]{"a","b","c"};
for(int i = 0 ;i < arr.length;i++){
String tem = arr[i];
arr[i] = arr[arr.length - i - 1];
arr[arr.length - i - 1] = tem;
}
//cba
String[] arr = new String[]{"a","b","c"};
String target = "a";
for(int i = 0 ;i < arr.length;i++){
if(target.equals(arr[i])){
System.out.print("找到指定元素,位置为"+i);
break;
}
}
前提:数组必须有序
int[] arr = new int[]{1,2,3,4,5,6,7,8,9,10};
//线性查找
int num = 2;
int start = 0; //初始首索引
int end = arr.length - 1; //初始尾索引
while(start <= end){
int middle = (start + end) / 2;
if(num == arr[middle]){
System.out.print("查找到该元素位置为"+middle);
break;
}else if(arr[middle] > num){
end = middle -1;
}else{
start = middle + 1;
}
}
基本思想:通过对待排序序列从前向后,依次比较相邻元素的排序码,若发现逆序则交换,使排序码较大的元素逐渐从前部移向后部。
int[] arr = new int[]{1,2,3,4,5,6,7,8,9,10};
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 tem = arr[j];
arr[j] = arr[j+1];
arr[j+1] = tem;
}
}
}
........