1. 程式人生 > >查找之一順序查找

查找之一順序查找

log color search stat == string while key 輸出結果

一、

 1 public class Sequential_SearchDemo01 {
 2     static int[] num = {1,3,4,6};
 3     public static void main(String[] args) {
 4         int key = 7;
 5         boolean x = Sequential_Search(key);
 6         System.out.println(x);
 7     }
 8     private static boolean Sequential_Search(int key) {
9 for(int i=0;i<num.length;i++){ 10 if(num[i] == key){ 11 return true; 12 } 13 } 14 return false; 15 } 16 }

輸出結果為:false

二、順序查找的優化

 1 public class Sequential_SearchDemo02 {
 2     static int[] num = {0,5,8,9,6,3};
 3     public static
void main(String[] args) { 4 int key = 7; 5 int x = Sequential_Search(key); 6 System.out.println(x); 7 } 8 private static int Sequential_Search(int key) { 9 int i; 10 num[0] = key; 11 i = num.length - 1; 12 while(num[i] != key){ 13
i--; 14 } 15 return i; 16 } 17 18 }

如果輸出為0,表示沒有查到key,;

時間復雜度為O(n)

查找之一順序查找