一、冒泡排序java
![](http://static.javashuo.com/static/loading.gif)
![](http://static.javashuo.com/static/loading.gif)
1 package cn.zh.abstrac; 2 3 import java.util.Arrays; 4 5 //冒泡排序 6 public class Demo019 { 7 public static void main(String[] args) { 8 int[] values = {22, 11, 33, 2, 4, 5, 66, 55, 44}; 9 int temp = 0; 10 for (int j = 0; j < values.length - 1 - j; j++) { 11 boolean flag = true; 12 for (int i = 0; i < values.length - 1; i++) { 13 //比較大小,換順序 14 if (values[i] > values[i + 1]) { 15 temp = values[i]; 16 values[i] = values[i + 1]; 17 values[i + 1] = temp; 18 19 flag = false; 20 } 21 } 22 if (flag) { 23 break; 24 } 25 } 26 System.out.println(Arrays.toString(values)); 27 } 28 }
運行結果圖app
二、二分法查找法ide
![](http://static.javashuo.com/static/loading.gif)
![](http://static.javashuo.com/static/loading.gif)
1 package cn.zh.abstrac; 2 3 import java.util.Arrays; 4 5 //二分法查找 6 public class TestBinarySearch { 7 public static void main(String[] args) { 8 int[] arr = {30, 20, 50, 10, 80, 9, 7, 12, 100, 40, 8}; 9 Arrays.sort(arr); 10 System.out.println(Arrays.toString(arr)); 11 System.out.println(myBinarySearch(arr,40)); 12 } 13 14 public static int myBinarySearch(int[] arr, int value){ 15 int low = 0; 16 int high = arr.length - 1; 17 18 while (low <= high) { 19 int mid = (low + high) / 2; 20 if (value == arr[mid]) { 21 return mid; 22 } 23 if (value > arr[mid]) { 24 low = mid + 1; 25 } 26 if (value < arr[mid]) { 27 high = mid - 1; 28 } 29 } 30 return -1; 31 } 32 }
運行結果圖ui
三、可變字符序列與不可變字符序列spa
注:循環累加用StringBuildercode
![](http://static.javashuo.com/static/loading.gif)
![](http://static.javashuo.com/static/loading.gif)
1 package cn.zh.abstrac; 2 3 public class TestStringBuilder { 4 public static void main(String[] args) { 5 //使用String進行字符串的拼接 6 String str1 = ""; 7 //本質上使用StringBuilder拼接,可是每次循環都會生成一個StringBuilder對象 8 long num1 = Runtime.getRuntime().freeMemory(); //獲取系統剩餘內存空間 9 //獲取系統的當前時間 10 long time1 = System.currentTimeMillis(); 11 for (int i = 0; i < 5000; i++) { 12 //至關於產生了10000個對象 13 str1 = str1 + i; 14 } 15 long num2 = Runtime.getRuntime().freeMemory(); 16 long time2 = System.currentTimeMillis(); 17 System.out.println("String佔用內存:" + (num1 - num2)); 18 System.out.println("String佔用時間:" + (time2 - time1)); 19 20 //使用StringBuilder進行字符串的拼接 21 StringBuilder sb1 = new StringBuilder(""); 22 long num3 = Runtime.getRuntime().freeMemory(); 23 long time3 = System.currentTimeMillis(); 24 for (int i = 0; i < 5000; i++) { 25 sb1.append(i); 26 } 27 long num4 = Runtime.getRuntime().freeMemory(); 28 long time4 = System.currentTimeMillis(); 29 System.out.println("StringBuilder佔用內存:" + (num3 - num4)); 30 System.out.println("StringBuilder佔用時間:" + (time4 - time3)); 31 } 32 }
運行結果圖對象
四、blog