
//写一个方法求数组的最大值。
public class TestDemo1 {
public static int maxNum(int[] array) {
int max = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] > max) {
max = array[i];
}
}
return max;
}
public static void main(String[] args) {
int[] array = {1, 2, 3, 4, 5, 6, 7};
System.out.println(maxNum(array));
}
} 2.二分查找(必须是针对有序的序列)。
//二分查找
public class TestDemo1 {
public static int binarysearch(int[] array,int key) {
int left = 0;
int right = array.length - 1;
while (left <= right) {
int mid = (left + right) / 2;//可以优化为右移一位,右移的速度比除法快
if (array[mid] > key) {
right = mid - 1;
}
else if (array[mid] < key) {
left = mid + 1;
}
else {
return mid;
}
}
return -1;
}
public static void main(String[] args) {
int[] array = {1,2,3,4,5,6,7,8,9};
int key = 8;
System.out.println(binarysearch(array,key));
}
//二分查找
public class TestDemo1 {
public static void main(String[] args) {
int[] array = {1,2,3,4,5,6};
System.out.println(Arrays.binarySearch(array,4));
}
3.判断一个数组是否是升序。 升序返回true,不是返回false。
//判断一个数组是否是升序的,是:true。不是:flase。
public class TestDemo1 {
public static boolean isUp(int[] array){
for (int i = 0;i < array.length-1;i++){
if (array[i]>array[i+1]){
return false;
}
}
return true;
}
public static void main(String[] args) {
int[] array = {1,2,3,10,5,6};
System.out.println(isUp(array));
}
}
4.冒泡排序。
//冒泡排序
public class TestDemo1 {
public static void bubbleSort(int[] array) {
for (int i = 0;i < array.length-1;i++){
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;
}
}
}
}
public static void main(String[] args) {
int[] array = {1,2,4,10,3,5,8};
bubbleSort(array);
System.out.println(Arrays.toString(array));
}
//优化冒泡排序
public class TestDemo1 {
public static void bubbleSort(int[] array) {
boolean flg = false;//没有发生交换
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) {
break;
}
}
}
public static void main(String[] args) {
int[] array = {1, 2, 4, 10, 3, 5, 8};
bubbleSort(array);
System.out.println(Arrays.toString(array));
}
}
5.逆置一个数组。
//数组逆置
public class TestDemo1 {
public static void reverse(int[] array) {
int left = 0;
int right = array.length - 1;
while (left <= right) {
int tmp = array[left];
array[left] = array[right];
array[right] = tmp;
left++;
right--;
}
}
public static void main(String[] args) {
int[] array = {1, 2, 3, 4, 5, 6, 7};
reverse(array);
System.out.println(Arrays.toString(array));
}
}
6.数组排列,偶数在前奇数在后。
//数组排列,偶数放到前面,奇数放到后面
public class TestDemo1 {
public static void swap(int[] array) {
int left = 0;
int right = array.length-1;
while (left < right) {
while (left