[abcdef] --> [efabcd]
思想:
1.前4个为一组逆序
2.后两个为一组逆序
3.整体逆序
冒泡排序:
1.例如 一共有n个元素,一共就需要进行n-1轮排序,也就是外层循环(n-1)次
2.每一轮循环后会确定一个最大的元素,以此类推
(外面一层控制排序的次数,里面的循环结束后会得到一个最大的元素在最后以为,以次类推)
public class maopao { public static void main(String[] args) { int arr[] = {1,3,4,7,2}; //冒泡排序 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 temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp; } } } for (int i : arr) { System.out.print(i+","); } } }
折半查找:
(必须是已经排好序)
1.定义 最小值,最大值,中间值[(low+high)/2]
2.若要查找的数值小于中间值,则high的位置指向mid的前一个位置(high = mid-1)
3.若要查找的数值大于中间值,则low的位置指向mid的后一个位置(low= mid+1)
4.查找到后返回mid,即要找的元素的索引值
public class BinarySearch { public static void main(String[] args) { int arr[] = {1,3,4,5,6,7,8,9}; int num = 3; int search = Search(arr, num); System.out.println("找到位置的索引为:"+search); } //折半查找法 public static int Search(int[] arr, int num) { int low = 0; int high = arr.length - 1; int mid;
//要找的数值小于最小值||大于最大值||最大值<最小值。。。返回-1
if(num < arr[low]||num > arr[high]||low > high){ return -1; } while (low <= high) { mid = (low + high) / 2; if (num < arr[mid]) { high = mid - 1; } else if (num > arr[mid]) { low = mid + 1; }else { return mid; } }
//未找到返回-1 return -1; } }
数组扩容:
public class ArrayAdd { public static void main(String[] args) { //数组扩容 int arr[] = {1, 2, 3}; Scanner sc = new Scanner(System.in); while (true) { System.out.println("是否追加元素?y/n"); String key = sc.next(); if (key.equals("y")) { System.out.println("请输入你要追加的元素:"); int num = sc.nextInt(); int arr1[] = new int[arr.length + 1]; for (int i = 0; i < arr.length ; i++) { arr1[i] = arr[i]; arr1[arr1.length - 1] = num; } arr = arr1;//扩容之后再把新数组的地址赋值给原数组 System.out.println(Arrays.toString(arr1)); }else if (key.equals("n")){ System.out.println("退出"); break; } } } }
数组反转:
public class ArrayReverse { public static void main(String[] args) { //数组反转 int arr[] = {1,2,3,4,5,6,7}; //需要交换arr.length/2 次 而不是arr.length次,否则又会变为原数组 for (int i = 0; i < arr.length/2; i++) { int temp = arr[arr.length -1 -i]; arr[arr.length -1 -i] = arr[i]; arr[i] = temp; } /*int[] newarr = new int[arr.length]; for (int i = 0; i < arr.length; i++) { newarr[i] = arr[arr.length - 1 - i]; }*/ System.out.println(Arrays.toString(arr)); } }