This is my "binary search"Algorithm"Java implementation!
View code
1 /* 2 * Exercise: Binary Search Algorithm 3 * Function: Find whether a data to be searched exists in a pile of data 4 * Author: Chen peirui 5 * Time: 2013.03.25 6 * Caution: This class import the package part01.charter02 for create a string sorted data 7 */ 8 Package Part01.chapter02; 9 10 Import Java. util. arraylist; 11 Import Java. util. List; 12 Import Java. util. vendor; 13 14 Public Class _ 2 exercise { 15 16 Public Static Void Main (string [] ARGs ){ 17 // Int [] A = {1, 3, 5, 7, 9, 2, 4, 6, 8, 10 }; 18 // Merge_sort = new merge_sort (); 19 // Merge_sort.sort (A, 0, 9 ); 20 // Create data 21 System. Out. println ("Please inter A int number for datum counts :" ); 22 Required bytes = New Using (system. In ); 23 Int Leng = Vertex. nextint (); 24 Createdate = New Createdate (Leng ); 25 Int [] A = Createdate. Create (); 26 // Sort data by merge_sort () 27 Merge_sort = New Merge_sort (); 28 Merge_sort.sort (A, 0, Leng-1 ); 29 // Output sorted data 30 System. Out. println ("the sorted data are follow :" ); 31 For ( Int I = 0; I <Leng; I ++ ){ 32 System. Out. Print (A [I] + "" ); 33 } 34 System. Out. println (); 35 Binaryfind mybinaryfind = New Binaryfind (); 36 System. Out. println ("Enter the number you want to find :" ); 37 If (Mybinaryfind. binaryfind (A, 0, A. Length-1 , Iterator. nextint ())){ 38 System. Out. println ("existence! " ); 39 } Else { 40 System. Out. println ("inexistence! " ); 41 } 42 } 43 } 44 45 Class Binaryfind { 46 Public Boolean Binaryfind ( Int [],Int P, Int R, Int S ){ // 0, 9, 3; 5, 9, 3; 47 // Flag sign existence or not 48 Boolean Flag = False ; 49 If (A. length> 0 & P <= R ){ 50 Int Q = (p + r ); // 2; 7; 51 If (A [Q] = s ){ // A [4] = 5; 8; 52 Flag = True ; 53 Return Flag; 54 } Else { 55 If (A [Q] < S ){ 56 Flag = binaryfind (A, q + 1 , R, S ); 57 } Else { 58 Flag = binaryfind (A, p, q-1, S ); // 5, 9; 59 } 60 } 61 } 62 Return Flag; 63 } 64 65 // Find number and return it's first substance 66 Public Int Find_first (Int [], Int P, Int R, Int S ){ 67 Int Sub = 0 ; 68 If (A. length> 0 ){ 69 For ( Int I = P; I <R + 1; I ++ ){ 70 If (A [I] = S ){ 71 Sub = I; 72 } 73 } 74 } 75 Return Sub; 76 } 77 78 // Find all same number and return all their substances 79 Public List <integer> find_all ( Int [], Int P, Int R, Int S ){ 80 // Create a integer list <integer> to store all same number's substances 81 List <integer> sublist = New Arraylist <integer> (); 82 If (A. length> 0 ){ 83 For ( Int I = P; I <r; I ++ ){ 84 If (A [I] = S ){ 85 Sublist. Add (I ); 86 } 87 } 88 } 89 Return Sublist; 90 } 91 }