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绛夛级銆