Detailed explanation of the Java sort, lookup, and hash table algorithm

Java sort and search algorithm summary

Sort
1) Internal sorting: refers to loading all the data that needs to be processed into the internal memory (memory)Sort in.
2) External sorting:
If the amount of data is too large, it cannot be loaded into memory and must be used
External storage (file, etc.) ** sorted.
3) Classification of common sorting algorithms:

(1) Bubble sorting
1. Algorithm thinking: sorting sequence processing from front to back (starting with the smallest element), the value of adjacent elements is compared in turn. It gradually rises like an underwater bubble.
Optimization: Due to the sorting process, each element is constantly getting closer to its position. If the comparison is not exchanged, it means that the sequence is ordered, so set the flag judgment element in the sort operation to determine whether the element element has been replaced. Which reduces unnecessary comparisons. (Optimization mentioned here
Clarification process:

Summary of the above process diagram:
(1) The total size of the large ring matrix is ​​-1
(2) The amount of sorting time is gradually decreasing
(3) If we find that there is no exchange in a certain type, the bubble sort can be completed in advance. This is optimal

2. Реализация кода:
public class BubbleSort {

	public static void main(String[] args) {




		
		
		
		
		
		int[] arr = new int[80000];
		for(int i =0; i < 80000;i++) {
			arr[i] = (int)(Math.random() * 8000000); 
		}
		
		Date data1 = new Date();
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String date1Str = simpleDateFormat.format(data1);
		System.out.println("Время перед сортировкой is =" + date1Str);
		
		
		bubbleSort(arr);
		
		Date data2 = new Date();
		String date2Str = simpleDateFormat.format(data2);
		System.out.println("Время после сортировки =" + date2Str);
		
		
		
		
		
		
		
	}
	
	
	public static void bubbleSort(int[] arr) {
		
		int temp = 0; 
		boolean flag = false; 
		for (int i = 0; i < arr.length - 1; i++) {

			for (int j = 0; j < arr.length - 1 - i; j++) {
				
				if (arr[j] > arr[j + 1]) {
					flag = true;
					temp = arr[j];
					arr[j] = arr[j + 1];
					arr[j + 1] = temp;
				}
			}
			
			

			if (!flag) { 
				break;
			} else {
				flag = false; 
			}
		}
	}

}

(2) Select Sort
1. Thought algorithm: Selection sort is a simple sort method. Main idea: Determine the minimum value in the first arr [0] ~ arr [n-1]exchange with ARR [0]the second time from R [1] ~ arr [n-1]exchange with ARR [1]select the minimum value of the ARR [2] ~ arr [n-1] Third time, exchange with ARR [2]… [i-1] ~ arr [n- 1] Specify the minimum value, and replace it with ARR [I-1]…, n -1 times the ARR [n-2] ~ arr [n-1] 2]Exchange, the total amount of the order from small to large reaches n-1 times within n-1 times.
Clarification process:


2. Code execution


public class SelectSort {

	public static void main(String[] args) {
		
		
		int[] arr = new int[80000];
		for (int i = 0; i < 80000; i++) {
			arr[i] = (int) (Math.random() * 8000000); 
		}
		System.out.println("Перед сортировкой");
		
		Date data1 = new Date();
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String date1Str = simpleDateFormat.format(data1);
		System.out.println("Время перед сортировкой is =" + date1Str);
		selectSort(arr);
		Date data2 = new Date();
		String date2Str = simpleDateFormat.format(data2);
		System.out.println("Время перед сортировкой is =" + date2Str);
		
		
	}
	
	
	public static void selectSort(int[] arr) {
		
		
		for (int i = 0; i < arr.length - 1; i++) {
			int minIndex = i;
			int min = arr[i];
			for (int j = i + 1; j < arr.length; j++) {
				if (min > arr[j]) { 
					min = arr[j]; 
					minIndex = j; 
				}
			}
			
			if (minIndex != i) {
				arr[minIndex] = arr[i];
				arr[i] = min;
			}
			
			
		}
		
	}

}

(3) Enter sort
1. Algorithm thinking: Look at the elements to be classified as an ordered table and an unordered table. Initially, the ordered table contains only one element. Take the first element of the unordered table each time, compare the order-sorting code with the order-item sorting code, and insert it into the appropriate position in the ordered table to make it the new order-order.
Clarification process:
2. Code execution

public class InsertSort {
	public static void main(String[] args) {
		
		
		int[] arr = new int[80000];
		for (int i = 0; i < 80000; i++) {
			arr[i] = (int) (Math.random() * 8000000); 
		}
		System.out.println("Перед сортировкой");
		Date data1 = new Date();
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String date1Str = simpleDateFormat.format(data1);
		System.out.println("Время перед сортировкой is =" + date1Str);
		
		insertSort(arr); 
		
		Date data2 = new Date();
		String date2Str = simpleDateFormat.format(data2);
		System.out.println("Время перед сортировкой is =" + date2Str);
		
		
	}
	
	public static void insertSort(int[] arr) {
		int insertVal = 0;
		int insertIndex = 0;
		
		for(int i = 1; i < arr.length; i++) {
			
			insertVal = arr[i];
			insertIndex = i - 1; 
	
			
			
			
			
			
			while (insertIndex >= 0 && insertVal < arr[insertIndex]) {
				arr[insertIndex + 1] = arr[insertIndex];
				insertIndex--;
			}
			
			
			
			if(insertIndex + 1 != i) {
				arr[insertIndex + 1] = insertVal;
			}
			
			
		}
		
		
	}

}

(4) Hill type
1. Algorithm thinking: hill sorting is a certain incremental record, and the number of sorting algorithms entered directly is used for each group; As a gradual reduction, the keywords that each group contains become larger and larger. when it decreases. to 1, the entire file is simply split into a group, and the algorithm stops
Clarification process:
2. Code execution:
1) In hill sorting, the ordered sequence is used to use the exchange method when inserting, and the sorting speed is checked.
2) In hill sorting, the ordered sequence is used at the input, and the sorting speed is tested

public class ShellSort {

	public static void main(String[] args) {
		
		
		
		int[] arr = new int[8000000];
		for (int i = 0; i < 8000000; i++) {
			arr[i] = (int) (Math.random() * 8000000); 
		}

		System.out.println("Перед сортировкой");
		Date data1 = new Date();
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String date1Str = simpleDateFormat.format(data1);
		System.out.println("Время перед сортировкой is =" + date1Str);
		
		
		shellSort2(arr);
		
		Date data2 = new Date();
		String date2Str = simpleDateFormat.format(data2);
		System.out.println("Время перед сортировкой is =" + date2Str);
		
		
	}

	
	
	
	public static void shellSort(int[] arr) {
		int temp = 0;
		int count = 0;
		
		for (int gap = arr.length / 2; gap > 0; gap /= 2) {
			for (int i = gap; i < arr.length; i++) {
				
				for (int j = i - gap; j >= 0; j -= gap) {
					
					if (arr[j] > arr[j + gap]) {
						temp = arr[j];
						arr[j] = arr[j + gap];
						arr[j + gap] = temp;
					}
				}
			}
			
		}
		
	}
	
	public static void shellSort2(int[] arr) {
		
		
		for (int gap = arr.length / 2; gap > 0; gap /= 2) {
			
			for (int i = gap; i < arr.length; i++) {
				int j = i;
				int temp = arr[j];
				if (arr[j] < arr[j - gap]) {
					while (j - gap >= 0 && temp < arr[j - gap]) {
						
						arr[j] = arr[j-gap];
						j -= gap;
					}
					
					arr[j] = temp;
				}

			}
		}
	}

}

(5) Quick Sort
1. Algorithm idea: QuickSort is an improvement of bubble sort. The basic idea is to split the sorted data into two parts of an independent part. Some data is smaller than all the data in another part. Then follow this method to quickly sort these two pieces of data. The entire sorting process can be iterative so that accessing all the data becomes an ordered sequence.
Clarification process:
2. Code execution

public class QuickSort {
	public static void main(String[] args) {
		
		
		
		int[] arr = new int[8000000];
		for (int i = 0; i < 8000000; i++) {
			arr[i] = (int) (Math.random() * 8000000); 
		}
		System.out.println("Перед сортировкой");
		Date data1 = new Date();
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String date1Str = simpleDateFormat.format(data1);
		System.out.println("Время перед сортировкой is =" + date1Str);
		quickSort(arr, 0, arr.length-1);
		Date data2 = new Date();
		String date2Str = simpleDateFormat.format(data2);
		System.out.println("Время перед сортировкой is =" + date2Str);
		
	}
	public static void quickSort(int[] arr,int left, int right) {
		int l = left; 
		int r = right; 
		
		int pivot = arr[(left + right) / 2];
		int temp = 0; 
		
		
		while( l < r) { 
			
			while( arr[l] < pivot) {
				l += 1;
			}
			
			while(arr[r] > pivot) {
				r -= 1;
			}
			
			
			if( l >= r) {
				break;
			}
			
			
			temp = arr[l];
			arr[l] = arr[r];
			arr[r] = temp;
			
			
			if(arr[l] == pivot) {
				r -= 1;
			}
			
			if(arr[r] == pivot) {
				l += 1;
			}
		}
		
		
		if (l == r) {
			l += 1;
			r -= 1;
		}
		
		if(left < r) {
			quickSort(arr, left, r);
		}
		
		if(right > l) {
			quickSort(arr, l, right);
		}
	}
}

(6) Merge and sort
1. Algorithm idea: Merge sort is a sort method implemented by combining ideas. This algorithm takes the classic “divide-and-conquer” (divide) strategy into a small problem, and then iteratively solves, and it will restore the “restore” invasion stage. Different responses during the separation phase, such as separation and treatment).
Clarification process:

2. Реализация кода
public class MergetSort {
	public static void main(String[] args) {
		
		
		
		int[] arr = new int[8000000];
		for (int i = 0; i < 8000000; i++) {
			arr[i] = (int) (Math.random() * 8000000); 
		}
		System.out.println("Перед сортировкой");
		Date data1 = new Date();
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String date1Str = simpleDateFormat.format(data1);
		System.out.println("Время перед сортировкой is =" + date1Str);
		
		int temp[] = new int[arr.length]; 
 		mergeSort(arr, 0, arr.length - 1, temp);
 		
 		Date data2 = new Date();
		String date2Str = simpleDateFormat.format(data2);
		System.out.println("Время перед сортировкой is =" + date2Str);
 		
 		
	}
	
	
	public static void mergeSort(int[] arr, int left, int right, int[] temp) {
		if(left < right) {
			int mid = (left + right) / 2; 
			
			mergeSort(arr, left, mid, temp);
			
			mergeSort(arr, mid + 1, right, temp);
			
			merge(arr, left, mid, right, temp);
			
		}
	}
	
	
	
	public static void merge(int[] arr, int left, int mid, int right, int[] temp) {
		
		int i = left; 
		int j = mid + 1; 
		int t = 0; 
		
		
		
		
		while (i <= mid && j <= right) {
			
			
			
			if(arr[i] <= arr[j]) {
				temp[t] = arr[i];
				t += 1;
				i += 1;
			} else { 
				temp[t] = arr[j];
				t += 1;
				j += 1;
			}
		}
		
		
		
		while( i <= mid) { 
			temp[t] = arr[i];
			t += 1;
			i += 1;	
		}
		
		while( j <= right) { 
			temp[t] = arr[j];
			t += 1;
			j += 1;	
		}
		
		
		
		t = 0;
		int tempLeft = left; 
		
		
		while(tempLeft <= right) { 
			arr[tempLeft] = temp[t];
			t += 1;
			tempLeft += 1;
		}
		
	}

}

(7) Primary screening
1. The algorithm thinks:
1) One is the integer number of digits up to the same number that can be compared with the same length, and the number of short digits up to zero is added. Then, starting from the lowest position, sort in turn. This becomes an ordered sequence from the lowest position to the highest position.
2) It appears difficult to understand. Let’s look at the graphical explanation steps and understand the basic sorting steps.
Clarification process:

2. Code execution

public class RadixSort {

	public static void main(String[] args) {
		int arr[] = { 53, 3, 542, 748, 14, 214};
		
		




		System.out.println("Перед сортировкой");
		Date data1 = new Date();
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String date1Str = simpleDateFormat.format(data1);
		System.out.println("Время перед сортировкой is =" + date1Str);
		
		radixSort(arr);
		
		Date data2 = new Date();
		String date2Str = simpleDateFormat.format(data2);
		System.out.println("Время перед сортировкой is =" + date2Str);
		
		System.out.println("После базовой сортировки" + Arrays.toString(arr));
		
	}

	
	public static void radixSort(int[] arr) {
		
		
		
		
		int max = arr[0]; 
		for(int i = 1; i < arr.length; i++) {
			if (arr[i] > max) {
				max = arr[i];
			}
		}
		
		int maxLength = (max + "").length();
		
		
		
		
		
		
		
		int[][] bucket = new int[10][arr.length];
		
		
		
		
		int[] bucketElementCounts = new int[10];
		
		
		
		
		for(int i = 0 , n = 1; i < maxLength; i++, n *= 10) {
			
			for(int j = 0; j < arr.length; j++) {
				
				int digitOfElement = arr[j] / n % 10;
				
				bucket[digitOfElement][bucketElementCounts[digitOfElement]] = arr[j];
				bucketElementCounts[digitOfElement]++;
			}
			
			int index = 0;
			
			for(int k = 0; k < bucketElementCounts.length; k++) {
				
				if(bucketElementCounts[k] != 0) {
					
					for(int l = 0; l < bucketElementCounts[k]; l++) {
						
						arr[index++] = bucket[k][l];
					}
				}
				
				bucketElementCounts[k] = 0;
				
			}
			
			
		}
		
		
		
	}
}

Basic sorting instructions:
1) Primary sorting is an extension of the traditional stem type, and the speed is fast.
2) Primary sort is the classic time-shifting space which consumes a lot of memory. When the big data is sorted, it is easy to raise an OutofmemoryError.
3) The base is stable when sorting. [Примечание: предполагая, что в последовательности записей, которая будет отсортирована, есть много записей с одинаковыми ключевыми словами. Если отсортируется, относительный порядок этих записей остается неизменным, то есть в исходной последовательности R [i] = p [j ] and p [i] to p [j]Sequentially after sorting, p [i] still until p [j], This sorting algorithm is called to be stable; Otherwise it is called unstable]
4) There are negative numbers. We don’t use base sort for sorting. If we want to support negative numbers, please see
summary (algorithm summary and comparison)
Comparison chart:
Explanation of related term:

  1. stability: if A was originally before B, and A = B, after sorting, A was still before B;
  2. unstable: if A was originally before B, and A = B, after sorting, A may appear after C;
  3. internal sorting: all sorting operations are done in memory;
  4. External sorting: because the data is too large, the data is placed on disk, and the sorted data can only be moved through disk and memory;
  5. Complex time: The time taken by the algorithm.
  6. Space complexity: Run the amount of memory required by the program.
  7. N: data scale
  8. K: the number of “barrels”
  9. In place: does not take up additional memory space
  10. Out of place: take up extra memory
    Find
    There are four types of search algorithms used in Java:
    1. sequential (linear) search
    2. Two point search/half search
    3. search interpolation
    4. Find Fibonacci
      (1) Sequence (linear) search
      There is a numeric column: {1,8,10,89,1000,1234}. The judgment number includes the name [последовательность] Requirement: If you find it, you will be prompted to find and give the value of the label.
      Code:
public class SeqSearch {

	public static void main(String[] args) {
		int arr[] = { 1, 9, 11, -1, 34, 89 };
		int index = seqSearch(arr, -11);
		if(index == -1) {
			System.out.println("Не найден");
		} else {
			System.out.println("Найдите, настройка =" + index);
		}
	}

	
	public static int seqSearch(int[] arr, int value) {
		
		for (int i = 0; i < arr.length; i++) {
			if(arr[i] == value) {
				return i;
			}
		}
		return -1;
	}

}

(2) Two-point search/half-point search
Two-point search: Please search for two-point search {1,8,10,89,1000,1234} in the ordered set, enter a number to see if the array exists, and find trades. this number.

Code:


public class BinarySearch {

	public static void main(String[] args) {
		
		int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 , 11, 12, 13,14,15,16,17,18,19,20 };
		

		


		
		List<Integer> resIndexList = binarySearch2(arr, 0, arr.length - 1, 1);
		System.out.println("resIndexList=" + resIndexList);
	}

	
	
	public static int binarySearch(int[] arr, int left, int right, int findVal) {
		

		
		if (left > right) {
			return -1;
		}
		int mid = (left + right) / 2;
		int midVal = arr[mid];

		if (findVal > midVal) { 
			return binarySearch(arr, mid + 1, right, findVal);
		} else if (findVal < midVal) { 
			return binarySearch(arr, left, mid - 1, findVal);
		} else {
			
			return mid;
		}

	}
	
	
	

	public static List<Integer> binarySearch2(int[] arr, int left, int right, int findVal) {

		System.out.println("hello~");
		
		if (left > right) {
			return new ArrayList<Integer>();
		}
		int mid = (left + right) / 2;
		int midVal = arr[mid];

		if (findVal > midVal) { 
			return binarySearch2(arr, mid + 1, right, findVal);
		} else if (findVal < midVal) { 
			return binarySearch2(arr, left, mid - 1, findVal);
		} else {





			
			List<Integer> resIndexlist = new ArrayList<Integer>();
			
			int temp = mid - 1;
			while(true) {
				if (temp < 0 || arr[temp] != findVal) {
					break;
				}
				
				resIndexlist.add(temp);
				temp -= 1; 
			}
			resIndexlist.add(mid);  
			
			
			temp = mid + 1;
			while(true) {
				if (temp > arr.length - 1 || arr[temp] != findVal) {
					break;
				}
				
				resIndexlist.add(temp);
				temp += 1; 
			}
			
			return resIndexlist;
		}

	}
}

(3) Paste the search
1) Introduction to the principle of interpolation search:
The interpolation search algorithm is similar to the two-point search. The difference is that the search for interpolation starts from the adaptive mean each time.
2) Equation of the average index in the semi-studied discovery, the low represents the left index to the left, and the high represents the right index to the right. The key is the discovery mentioned earlier.
3) int mid = low + (high – low) * (key – arr[low]) / (arr[high] – Ar[low]); /interpolation index/ Corresponding code syntax: int mid = left + (right – left) * (findval – arr [слева]) / (arr [right] – Ar [слева])

Code:

public class InsertValueSearch {

	public static void main(String[] args) {
		




		
		int arr[] = { 1, 8, 10, 89,1000,1000, 1234 };
		
		int index = insertValueSearch(arr, 0, arr.length - 1, 1234);
		
		System.out.println("index = " + index);
		
		
	}
	
	public static int binarySearch(int[] arr, int left, int right, int findVal) {
		System.out.println("Два -точечный поиск называется ~");
		
		if (left > right) {
			return -1;
		}
		int mid = (left + right) / 2;
		int midVal = arr[mid];

		if (findVal > midVal) { 
			return binarySearch(arr, mid + 1, right, findVal);
		} else if (findVal < midVal) { 
			return binarySearch(arr, left, mid - 1, findVal);
		} else {

			return mid;
		}

	}

	
	
	
	public static int insertValueSearch(int[] arr, int left, int right, int findVal) { 

		System.out.println("Вставка количество раз ~~");
		
		
		
		if (left > right || findVal < arr[0] || findVal > arr[arr.length - 1]) {
			return -1;
		}

		
		int mid = left + (right - left) * (findVal - arr[left]) / (arr[right] - arr[left]);
		int midVal = arr[mid];
		if (findVal > midVal) { 
			return insertValueSearch(arr, mid + 1, right, findVal);
		} else if (findVal < midVal) { 
			return insertValueSearch(arr, left, mid - 1, findVal);
		} else {
			return mid;
		}

	}
}

Enter search precautions:

  1. In a large amount of data and a relatively unified search table, the keyword distribution finds interpolation, and the speed is faster.
  2. In the case where the keyword distribution is uneven, this method is not necessarily better than folding half of the search.
    (4) Fair detection of Fibonacci
    Fibonil (Golden Section) Find a basic introduction:
  3. Golden point segmentation refers to dividing a line segment into two parts, which is equivalent to another segment to another segment to the same segment of that segment. The approximate value of the first three digits is 0.618. Because the shape designed according to this share is very beautiful, it is called the golden division, also known as the Chinese and foreign share. This is a magic number that will bring a little bit of intention.
  4. Fibonacci number quantity {1, 1, 2, 3, 5, 8, 13, 21, 34, 55} Discover the fraction of two adjacent numbers of the Fibonacci column, which is infinitely close to the value of dividing gold 0.618
    Fibonacci Principles (Gold):
    The principle of searching is similar to the first and second levonels, which only changed the position of the middle (center) node. The average is no longer derived from the average or interpolation, but is located near the golden segmentation point, that is, average = Low + f (k- k- 1) -1 (F represents Fibona cycus), as shown in the figure below

    Understand f (k -1) -1:
  5. The nature of the F Fibonacci number [k] = f [K-1]+ and [K-2] can get (f [k] -1) = (p [k-1] -1) + ((p [f [f [f [f [f [f [f [f [f [f [f [f [f K -1] -1) + (F [K -2] -1) +1. This kind of explanation: As long as the length of the sequential table is f [k] -1, the table can be divided into two parts of length f [k -1] -1 and f [K -2] – 1, which, as shown in the figure above, is shown. Therefore, the middle position is medium = low + f(k-1)-1
  6. Similarly, each sub-task section can be divided equally
  7. However, the sequential length of table N is not necessarily equal to F [K] -1, so the length of the original serialized table N must be increased to f [k] -One. The value of k here may cause F [K] -1 is greater than or equal to n. From the following code, after increasing the length of the sequence table, the new position (from N+1 to f [k] – 1 position) N position value can be provided.
    while (n > fib (k) -1)
    k++;
    Code:
public class FibonacciSearch {

	public static int maxSize = 20;
	public static void main(String[] args) {
		int [] arr = {1,8, 10, 89, 1000, 1234};
		
		System.out.println("index=" + fibSearch(arr, 189));
		
	}

	
	
	public static int[] fib() {
		int[] f = new int[maxSize];
		f[0] = 1;
		f[1] = 1;
		for (int i = 2; i < maxSize; i++) {
			f[i] = f[i - 1] + f[i - 2];
		}
		return f;
	}
	
	
	
	
	public static int fibSearch(int[] a, int key) {
		int low = 0;
		int high = a.length - 1;
		int k = 0; 
		int mid = 0; 
		int f[] = fib(); 
		
		while(high > f[k] - 1) {
			k++;
		}
		
		
		int[] temp = Arrays.copyOf(a, f[k]);
		
		
		
		for(int i = high + 1; i < temp.length; i++) {
			temp[i] = a[high];
		}
		
		
		while (low <= high) { 
			mid = low + f[k - 1] - 1;
			if(key < temp[mid]) { 
				high = mid - 1;
				
				
				
				
				
				
				
				k--;
			} else if ( key > temp[mid]) { 
				low = mid + 1;
				
				
				
				
				
				
				
				k -= 2;
			} else { 
				
				if(mid <= high) {
					return mid;
				} else {
					return high;
				}
			}
		}
		return -1;
	}
}

hash table
Hash Table (shalement) – Google Embedded Questions

  1. Look at the actual needs, Google’s question on the board:
  2. There is a company that has a new employee who reports, and asks for employee information (ID, gender, age, address…). When you enter the employee ID, you should find all employee information. 3) Requirements: do not use a database, try to save memory as much as possible, the faster the speed, the better the hash table => (customize)
    Basic introduction to hash table:
    Scatter list (also known as hash table) is a data structure that is accessed directly according to the keycode value. In other words, it accesses the record by matching the keycode value with the position in the table in order to speed up the search speed. This mapping function is called the scatter function, and the set of registered entries is called the distribution list.

    There is a company that requests employee information when there is a new employee to report (ID, gender, age, name, address…). When you enter the employee ID, you need to find all employee information. wanted:
  3. Don’t use a database, the faster the better => hash (distribution) table
  4. When added, it is guaranteed to be listed from low id to high id [мышления после класса: если идентификатор не вставлен с низкого до высокого уровня, но связанные списки должны быть решены от низкого до высокого уровня, как его решить? ]
  5. Use the linked list to access the hash table. The linked list does not have a header [то есть первого узла связанного списка будет хранить информацию о сотруднике]]
  6. Analyze and draw the diagram

    Code:
public class HashTabDemo {

	public static void main(String[] args) {
		
		
		HashTab hashTab = new HashTab(7);
		
		
		String key = "";
		Scanner scanner = new Scanner(System.in);
		while(true) {
			System.out.println("Добавить: добавить сотрудников");
			System.out.println("Список: показать сотрудника");
			System.out.println("Найти: найти сотрудников");
			System.out.println("Выход: система выхода");
			
			key = scanner.next();
			switch (key) {
			case "add":
				System.out.println("Введите ID");
				int id = scanner.nextInt();
				System.out.println("Введите имя");
				String name = scanner.next();
				
				Emp emp = new Emp(id, name);
				hashTab.add(emp);
				break;
			case "list":
				hashTab.list();
				break;
			case "find":
				System.out.println("Пожалуйста, введите идентификатор, который вы хотите найти");
				id = scanner.nextInt();
				hashTab.findEmpById(id);
				break;
			case "exit":
				scanner.close();
				System.exit(0);
			default:
				break;
			}
		}
		
	}

}


class HashTab {
	private EmpLinkedList[] empLinkedListArray;
	private int size; 
	
	
	public HashTab(int size) {
		this.size = size;
		
		empLinkedListArray = new EmpLinkedList[size];
		
		for(int i = 0; i < size; i++) {
			empLinkedListArray[i] = new EmpLinkedList();
		}
	}
	
	
	public void add(Emp emp) {
		
		int empLinkedListNO = hashFun(emp.id);
		
		empLinkedListArray[empLinkedListNO].add(emp);
		
	}
	
	public void list() {
		for(int i = 0; i < size; i++) {
			empLinkedListArray[i].list(i);
		}
	}
	
	
	public void findEmpById(int id) {
		
		int empLinkedListNO = hashFun(id);
		Emp emp = empLinkedListArray[empLinkedListNO].findEmpById(id);
		if(emp != null) {
			System.out.printf("Найдите идентификатор сотрудника = %d \ n", (empLinkedListNO + 1), id);
		}else{
			System.out.println("В хэш -таблице не было найдено ни одного сотрудника ~");
		}
	}
	
	
	public int hashFun(int id) {
		return id % size;
	}
	
	
}


class Emp {
	public int id;
	public String name;
	public Emp next; 
	public Emp(int id, String name) {
		super();
		this.id = id;
		this.name = name;
	}
}


class EmpLinkedList {
	
	private Emp head; 
	
	
	
	
	
	public void add(Emp emp) {
		
		if(head == null) {
			head = emp;
			return;
		}
		
		Emp curEmp = head;
		while(true) {
			if(curEmp.next == null) {
				break;
			}
			curEmp = curEmp.next; 
		}
		
		curEmp.next = emp;
	}
	
	
	public void list(int no) {
		if(head == null) { 
			System.out.println(""+(no+1)+"Связанный список пуст");
			return;
		}
		System.out.print(""+(no+1)+"Информация о связанном списке - это");
		Emp curEmp = head; 
		while(true) {
			System.out.printf(" => id=%d name=%s\t", curEmp.id, curEmp.name);
			if(curEmp.next == null) {
				break;
			}
			curEmp = curEmp.next; 
		}
		System.out.println();
	}
	
	
	
	public Emp findEmpById(int id) {
		
		if(head == null) {
			System.out.println("Связанный список пуст");
			return null;
		}
		
		Emp curEmp = head;
		while(true) {
			if(curEmp.id == id) {
				break;
			}
			
			if(curEmp.next == null) {
				curEmp = null;
				break;
			}
			curEmp = curEmp.next;
		}
		
		return curEmp;
	}
	
}

Leave a Comment