日撸代码300行:第41天(顺序查找与折半查找)

本文档介绍了使用Java编写的DataArray类,包含顺序搜索(sequentialSearch)和二分查找(binarySearch)方法,用于搜索和排序数据。通过实例展示了如何创建数据节点并进行基本操作,以及在测试方法中对数组进行搜索演示。
摘要由CSDN通过智能技术生成

代码来自闵老师”日撸 Java 三百行(41-50天)“,链接:https://blog.csdn.net/minfanphd/article/details/116975863

package datastructure.search;

/**
 * Data array for searching and sorting algorithms.
 * 
 * @author WX873
 *
 */

public class DataArray {
	/**
	 * An inner class for data nodes. The text book usually use an int value to
	 * represent the data. I would like to use a key-value pair instead.
	 * @author WX873
	 *
	 */
	class DataNode{
		/**
		 * The key.
		 */
		int key;
		
		/**
		 * The content.
		 */
		String content;
		
		/**
		 * *******************************************************************
		 * The first constructor of class DataNode.
		 * 
		 * @param parakey
		 * @param paraString
		 * *******************************************************************
		 */
		public DataNode(int parakey, String paraString) {
			// TODO Auto-generated constructor stub
			key = parakey;
			content = paraString;
		}//First constructor of class DataNode.
		
		/**
		 * **********************************************************************
		 * overrides the method claimed in Object, the superclass of any class.
		 * **********************************************************************
		 */
		public String toString() {
			return "(" + key + ", " + content + ") ";
		}//of toString
	}//of class DataNode
	
	/**
	 * The data array.
	 */
	DataNode[] data;
	
	/**
	 * The length of the data array.
	 */
	int length;
	
	/**
	 * ********************************************************************
	 * The first constructor of class DataArray.
	 * 
	 * @param paraKeyArray    The array of the keys.
	 * @param paraContentArray   The array of contents.
	 * ********************************************************************
	 */
	public DataArray(int[] paraKeyArray, String[] paraContentArray) {
		// TODO Auto-generated constructor stub
		length = paraKeyArray.length;
		data = new DataNode[length];
				
		for (int i = 0; i < length; i++) {
			data[i] = new DataNode(paraKeyArray[i], paraContentArray[i]);
		}//of for i
	}//The first constructor of class DataArray.
	
	/**
	 * **********************************************************************
	 * overrides the method claimed in Object, the superclass of any class.
	 * **********************************************************************
	 */
	public String toString() {
		String resultString = "I am a data array with \" + length + \" items.\r\n";
		
		for (int i = 0; i < length; i++) {
			resultString += data[i] + " ";
		}//of for i
		
		return resultString;
	}//of toString
	
	/**
	 * *********************************************************************
	 * Sequential Search.
	 * 
	 * @param paraKey   The given key.
	 * @return          The content of the key.
	 * *********************************************************************
	 */
	public String sequentialSearch(int paraKey) {
		data[0].key = paraKey;
		int i;
		for (i = length -1; data[i].key != paraKey; i--) {
			;
		}//of for i
		return data[i].content;
	}//of sequentialSearch
	
	/**
	 * *******************************************************************
	 * Test the method.
	 * *******************************************************************
	 */
	public static void sequentialSearchTest() {
		int[] tempUnsortedKeys = { -1, 5, 3, 6, 10, 7, 1, 9 };
		String[] tempContents = { "null", "if", "then", "else", "switch", "case", "for", "while" };
		DataArray tempDataArray = new DataArray(tempUnsortedKeys, tempContents);
		
		System.out.println(tempDataArray);
		System.out.println("Search result of 10 is: " + tempDataArray.sequentialSearch(10));
		System.out.println("Search result of 5 is: " + tempDataArray.sequentialSearch(5));
		System.out.println("Search result of -1 is: " + tempDataArray.sequentialSearch(-1));
		System.out.println("Search result of 4 is: " + tempDataArray.sequentialSearch(4));
	}//of sequentialSearchTest
	
	/**
	 * *******************************************************************
	 * Binary search. Attention: It is assume that keys are sorted
	 * in ascending order.
	 * 
	 * @param paraKey  The given key.
	 * @return    The content of the key.
	 * *******************************************************************
	 */
	public String binarySearch(int paraKey) {
		int tempLeft = 0;
		int tempRight = length - 1;
		int tempMiddle = (tempLeft + tempRight) / 2;
		
		while (tempLeft <= tempRight) {
			tempMiddle = (tempLeft + tempRight) / 2;
			if (data[tempMiddle].key == paraKey) {
				return data[tempMiddle].content;
			}else if (data[tempMiddle].key < paraKey) {
				tempLeft = tempMiddle + 1;
			}else {
				tempRight = tempMiddle - 1;
			}//of if
		}//of while
		
		//Not found.
		return "Not found";
	}//of binarySearch
	
	public static void binarySearchTest() {
		int[] tempSortedKeys = { 1, 3, 5, 6, 7, 9, 10 };
		String[] tempContents = { "if", "then", "else", "switch", "case", "for", "while" };
		DataArray tempDataArray = new DataArray(tempSortedKeys, tempContents);
		
		System.out.println(tempDataArray);
		System.out.println("Search result of 10 is: " + tempDataArray.binarySearch(10));
		System.out.println("Search result of 5 is: " + tempDataArray.binarySearch(5));
		System.out.println("Search result of 4 is: " + tempDataArray.binarySearch(4));
	}//of binarySearchTest
	
	/**
	 * The entrance of program.
	 * @param args  Not used now.
	 */
	public static void main(String args[]) {
		System.out.println("\r\n-------sequentialSearchTest-------");
		sequentialSearchTest();
		
		System.out.println("\r\n-------binarySearchTest-------");
		binarySearchTest();
	}//of main

}//of DataArray

1、方法sequentialSearchTest()的测试数组第一个键值对必须为-1和null,否则程序就有逻辑错误。输入数组里没有的数字,就会找到第一个键值对对应的content。尝试了修改代码使data[0]固定为-1和null,这样测试的时候数组前两个就不需固定。尝试成功了,但是下面的折半查找还需要用到DataArray(int[] paraKeyArray, String[] paraContentArray),就又改回来了。
2、折半查找自己写的时候,写丢了while循环里的一行代码“tempMiddle = (tempLeft + tempRight) / 2;”,导致出现死循环。还有就是else和else if里的加一减一是必须的,否则也会出现死循环。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值