2021-09-04
阿新 • • 發佈:2021-09-04
[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 (inti = 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)); } }