_ Linear search algorithm and a binary search

com.atguigu.exer Package; 

/ * 
 * 1. linear search 
 * search the given values in a column, checking each element from an end of the start process until you find the desired element. 
 * Linear search is also called sequential search. 
 * 2. Find dichotomy 
 * dichotomy Look for the large amount of data, but the data need to be in good order. 
 * / 

Public class ArrayTest1 { 
	public static void main (String [] args) { 
		// find the linear 1. 
		// string array 
		String [] arrStr = new String [ ] { "AA", "BB", "CC", "DD", "EE"}; 
		// iterate 
		for (int I = 0; I <arrStr.length; I ++) { 
			of System.out.print (arrStr [I] + ""); 
		} 
		System.out.println (); 

		string objStr = "BB"; // destination string 
		boolean flag = true; // identity 
		// specified element found 
		for (int i = 0; i <arrStr.
			IF (objStr.equals (arrStr [I])) { 
		boolean flag1 = true; // identification
				System.out.println ( "finds the specified element location is:" + I); 
				In Flag to false =; 
				BREAK; 
			} 
		} 
		// do not find the specified element 
		IF (In Flag) { 
			System.out.println ( "did not find the specified element "); 
		} 
		System.out.println (); 

		
		
		// binary search 2. (provided: the sought number is ordered) 
		// integer array 
		int [] arrNum = new int [ ] {12, 24, 36, 48, 56, 76, 88, 94}; 
		// iterate 
		for (int I = 0; I <arrNum.length; I ++) { 
			of System.out.print (arrNum [I] + ""); 
		} 
		the System .out.println (); 
		
		int objNum = 48; // number to be searched 
		int head = 0; // header index 
		int end = arrNum.length - 1; // End index
		the while (head <= End) { 
			int = MID (End head +) / 2; // index intermediate position 
			if (objNum == arrNum [mid] ) {// find 
				System.out.println ( "finds the specified element , location is: "+ MID); 
				FLAG1 = to false; // If the element is found, then the change FLAG1 
				BREAK; 
			} the else IF (objNum <arrNum [MID]) { 
				End = MID -. 1; 
			} // the else {objNum> arrNum [MID] 
				head. 1 + = MID; 
			} 
		} 
		// not found (no change FLAG1) 
		IF (FLAG1) { 
			System.out.println ( "did not find the specified element"); 
		} 
		

	} 
}

  

Guess you like

Origin www.cnblogs.com/stefaniee/p/10930767.html