A. 鍏充簬java鐨刡inarySearch錛堬級鏂規硶
binarysearch涓哄湪鎸囧畾鏁扮粍涓鏌ユ壘鎸囧畾鍊煎緱緔㈠紩鍊礆紝璇ュ煎湪鑼冨洿鍐呮壘寰楀埌鍒欒繑鍥炶ュ肩殑緔㈠紩鍊礆紝鎵句笉鍒板垯榪斿洖璇ュ肩殑鎻掑叆浣嶇疆錛屽傛灉璇ュ煎ぇ浜庢寚瀹氳寖鍥存渶澶у煎垯榪斿洖-錛坢axlength+1錛夛紝鑰岋細
int w=Arrays.binarySearch(a,1,5,8); 鏌ユ壘鐨勮寖鍥翠負緔㈠紩鍊1-5,錛2,3,4,5,6
8騫朵笉鍦ㄦよ寖鍥翠腑錛屼笖8澶т簬鏈澶х儲寮曞肩殑6錛屾墍浠ヨ繑鍥-錛5+1錛夛細-6
鏌ョ湅java婧愮爜錛屽彲浠ョ湅鍒幫紝binarySearch錛堬級鏂規硶鏄閲嶈澆鏂規硶錛屾彁渚涗簡涓ょ嶅艦鍙傛柟寮忥細
灝忚創澹錛歜inarySearch錛堬級鏂瑰紡鍐呴儴瀹炵幇鐢ㄧ殑鏄浜屽垎娉曟煡鎵撅紝鎵浠ュ湪鏌ユ壘鍓嶉渶瑕佸皢鏁扮粍榪涜屾帓搴忥紝涓旀暟緇勪腑涓嶈兘鍑虹幇鐩稿悓鍏冪礌錛屽惁鍒欐煡鎵懼嚭鏉ョ殑緔㈠紩浼氫笉娓呮氭槸鍝涓涓鐨勶細
1錛夐粯璁よ寖鍥達紙鏁扮粍闀垮害錛夋煡鎵炬寚瀹氬肩儲寮曪細
鏍煎紡錛
binarySearch(object[ ], object key);
濡傛灉key鍦ㄦ暟緇勪腑錛屽垯榪斿洖鎼滅儲鍊肩殑緔㈠紩錛涘惁鍒欒繑鍥-1錛坘ey灝忎簬鏁扮粍涓鐨勪換鎰忎竴涓鍏冪礌錛夋垨鑰呪-鈥(鎻掑叆鐐)銆傛彃鍏ョ偣鏄緔㈠紩閿灝嗚佹彃鍏ユ暟緇勭殑閭d竴鐐癸紝鍗崇涓涓澶т簬璇ラ敭鐨勫厓緔犵儲寮曘
key鐨勫煎湪鏁扮粍鑼冨洿鍐呭垯緔㈠紩浠0寮濮嬭℃暟錛
key鍊間笉瀛樺湪鏁扮粍鑼冨洿鍐咃紙澶т簬鏁扮粍鏈灝忓厓緔狅級鍒欎粠1寮濮嬭℃暟錛
瀹炰緥錛
importjava.util.Arrays;publicclasstest {publicstaticvoidmain(String[] args){int[]b=newint[]{4,25,10,95,06,21};System.out.println("鍘熸暟緇勪負錛");for(intdim1:b){System.out.print(""+dim1+" ");}Arrays.sort(b);System.out.println("鎺掑簭鍚庝負錛");for(intx:b){System.out.print(x+" ");}System.out.println();intindex=Arrays.binarySearch(b,2);System.out.println("鍏抽敭瀛2鐨勮繑鍥炲間負錛"+index);index=Arrays.binarySearch(b,20);System.out.println("鍏抽敭瀛20鐨勮繑鍥炲間負錛"+index);index=Arrays.binarySearch(b,30);System.out.println("鍏抽敭瀛30鐨勮繑鍥炲間負錛"+index);index=Arrays.binarySearch(b,100);System.out.println("鍏抽敭瀛100鐨勮繑鍥炲間負錛"+index);index=Arrays.binarySearch(b,10);System.out.println("鍏抽敭瀛10鐨勮繑鍥炲間負錛"+index);}}
//out:
鏁扮粍瀵逛簬姣忎竴闂ㄧ紪紼嬭璦鏉ヨ撮兘鏄閲嶈佺殑鏁版嵁緇撴瀯涔嬩竴錛屽綋鐒朵笉鍚岃璦瀵規暟緇勭殑瀹炵幇鍙婂勭悊涔熶笉灝界浉鍚屻
Java 璇璦涓鎻愪緵鐨勬暟緇勬槸鐢ㄦ潵瀛樺偍鍥哄畾澶у皬鐨勫悓綾誨瀷鍏冪礌銆
浣犲彲浠ュ0鏄庝竴涓鏁扮粍鍙橀噺錛屽 numbers[100] 鏉ヤ唬鏇跨洿鎺ュ0鏄 100 涓鐙絝嬪彉閲 number0錛宯umber1錛....錛宯umber99銆
鏈鏁欑▼灝嗕負澶у朵粙緇 Java 鏁扮粍鐨勫0鏄庛佸壋寤哄拰鍒濆嬪寲錛屽苟緇欏嚭鍏跺瑰簲鐨勪唬鐮併
Arrays 綾
java.util.Arrays 綾昏兘鏂逛究鍦版搷浣滄暟緇勶紝瀹冩彁渚涚殑鎵鏈夋柟娉曢兘鏄闈欐佺殑銆
鍏鋒湁浠ヤ笅鍔熻兘錛
緇欐暟緇勮祴鍊礆細閫氳繃 fill 鏂規硶銆
瀵規暟緇勬帓搴忥細閫氳繃 sort 鏂規硶,鎸夊崌搴忋
姣旇緝鏁扮粍錛氶氳繃 equals 鏂規硶姣旇緝鏁扮粍涓鍏冪礌鍊兼槸鍚︾浉絳夈
鏌ユ壘鏁扮粍鍏冪礌錛氶氳繃 binarySearch 鏂規硶鑳藉規帓搴忓ソ鐨勬暟緇勮繘琛屼簩鍒嗘煡鎵炬硶鎿嶄綔銆
1 public static int binarySearch(Object[] a, Object key)
鐢ㄤ簩鍒嗘煡鎵劇畻娉曞湪緇欏畾鏁扮粍涓鎼滅儲緇欏畾鍊肩殑瀵硅薄(Byte,Int,double絳)銆傛暟緇勫湪璋冪敤鍓嶅繀欏繪帓搴忓ソ鐨勩傚傛灉鏌ユ壘鍊煎寘鍚鍦ㄦ暟緇勪腑錛屽垯榪斿洖鎼滅儲閿鐨勭儲寮曪紱鍚﹀垯榪斿洖 (-(鎻掑叆鐐) - 1)銆
2 public static boolean equals(long[] a, long[] a2)
濡傛灉涓や釜鎸囧畾鐨 long 鍨嬫暟緇勫郊姝ょ浉絳夛紝鍒欒繑鍥 true銆傚傛灉涓や釜鏁扮粍鍖呭惈鐩稿悓鏁伴噺鐨勫厓緔狅紝騫朵笖涓や釜鏁扮粍涓鐨勬墍鏈夌浉搴斿厓緔犲歸兘鏄鐩哥瓑鐨勶紝鍒欒や負榪欎袱涓鏁扮粍鏄鐩哥瓑鐨勩傛崲鍙ヨ瘽璇達紝濡傛灉涓や釜鏁扮粍浠ョ浉鍚岄『搴忓寘鍚鐩稿悓鐨勫厓緔狅紝鍒欎袱涓鏁扮粍鏄鐩哥瓑鐨勩傚悓鏍風殑鏂規硶閫傜敤浜庢墍鏈夌殑鍏朵粬鍩烘湰鏁版嵁綾誨瀷錛圔yte錛宻hort錛孖nt絳夛級銆
3 public static void fill(int[] a, int val)
灝嗘寚瀹氱殑 int 鍊煎垎閰嶇粰鎸囧畾 int 鍨嬫暟緇勬寚瀹氳寖鍥翠腑鐨勬瘡涓鍏冪礌銆傚悓鏍風殑鏂規硶閫傜敤浜庢墍鏈夌殑鍏朵粬鍩烘湰鏁版嵁綾誨瀷錛圔yte錛宻hort錛孖nt絳夛級銆
4 public static void sort(Object[] a)
瀵規寚瀹氬硅薄鏁扮粍鏍規嵁鍏跺厓緔犵殑鑷鐒墮『搴忚繘琛屽崌搴忔帓鍒椼傚悓鏍風殑鏂規硶閫傜敤浜庢墍鏈夌殑鍏朵粬鍩烘湰鏁版嵁綾誨瀷錛圔yte錛宻hort錛孖nt絳夛級銆