解题思路:
将组内元素由小到大排序 //冒泡排序
建立 left , right 分别指向数组两端数据
建立mid = (left + right)/2 ; //中间值
通过对比寻找数值key与中间值mid
key > mid 则令left = mid + 1;
key < mid 则令right = mid - 1;
代码实现:
public static void bubbleSort(int[] array) {
boolean flg = false;
//i 趟数
for (int i = 0; i < array.length-1; i++) {
flg = false;
for(int j = 0; j < array.length-1-i;j++) {
if(array[j] > array[j+1]) {
int tmp = array[j];
array[j] = array[j+1];
array[j+1] = tmp;
flg = true;
}
}
if(flg == false) {
return;
//判断是否交换,未交换说明已经有序
}
}
}
public static int binarySearch(int[] array,int key) {
int left = 0;
int right = array.length-1;
while (left <= right) {
count++;
int mid = (left+right)/2;
if(array[mid] == key) {
return mid;
}else if(array[mid] < key) {
left = mid+1;
}else {
right = mid-1;
}
}
return -1;//没有找到目标数字
}
解题思路:
定义两个下标分别在首尾两端
逐个交换两下标的值
代码实现:
public static void reverse(int[] array) {
if(array == null) {
return;
}//判断数组是否为空
int i = 0;
int j = array.length-1;
while (i < j) {
int tmp = array[i];
array[i] = array[j];
array[j] = tmp;
i++;
j--;
}
}
解题思路:
建立 i, j两个下标指向数组两端,先判断i是否为偶数,i 为偶数 i ++,
i 为奇数判断 j 的奇偶性,j 为奇数时交换,j为偶数时 j - -,
当 i = j 时结束循环返回数组
代码实现:
public static void func(int[] array) {
if(array == null) return;
int i = 0;
int j = array.length-1;
while (i < j) {
while ( i < j && array[i] % 2 == 0) {
i++;
}
while (i < j && array[j] % 2 != 0) {
j--;
}
int tmp = array[i];
array[i] = array[j];
array[j] = tmp;
}
}
- 二维数组的三种打印方法
int[][] array = {{1,2,3},{4,5,6},{7,8,9}};
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
System.out.print (array[i][j] +" ");
}
System.out.println();
}
//第一种易理解但冗长
for (int[] arr:array) {
for (int x : arr) {
System.out.print(x +" ");
}
System.out.println();
}
//第二张foreach方法简练
String ret = Arrays.deepToString(array);
System.out.println(ret);
//第三种方法打印出的数组带有中括号