search
HomeJavajavaTutorialJava data structure sorting algorithm (1) Tree selection sorting

This article mainly introduces the tree shape of java data structure sorting algorithmselection sorting, combined with specific examples to analyze the principles, implementation skills and related precautions of java tree selection sorting, friends in need You can refer to the following

The example of this article describes the tree selection sorting algorithm of java data structure. Share it with everyone for your reference, the details are as follows:

Here we will talk about the sorting of one of the selection types: tree selection sorting

In simple selection sorting, each comparison The results of the last comparison are not used, so the time complexity of the comparison operation is O(N^2). If you want to reduce the number of comparisons, you need to save the size relationship during the comparison process. Tree selection sort is an improvement over simple selection sort.

Tree selection sorting: Also known as Tournament Sort), is a sorting based on the championship Think about the method of selection sorting. First perform a pairwise comparison of the keywords of n records, and then perform a pairwise comparison between the n/2 smaller ones, and repeat this until the smallest record is selected.

Algorithm implementation code is as follows:

package exp_sort;
public class TreeSelectSort {
 public static int[] TreeSelectionSort(int[] mData) {
  int TreeLong = mData.length * 4;
  int MinValue = -10000;
  int[] tree = new int[TreeLong]; // 树的大小
  int baseSize;
  int i;
  int n = mData.length;
  int max;
  int maxIndex;
  int treeSize;
  baseSize = 1;
  while (baseSize < n) {
   baseSize *= 2;
  }
  treeSize = baseSize * 2 - 1;
  for (i = 0; i < n; i++) {
   tree[treeSize - i] = mData[i];
  }
  for (; i < baseSize; i++) {
   tree[treeSize - i] = MinValue;
  }
  // 构造一棵树
  for (i = treeSize; i > 1; i -= 2) {
   tree[i / 2] = (tree[i] > tree[i - 1] ? tree[i] : tree[i - 1]);
  }
  n -= 1;
  while (n != -1) {
   max = tree[1];
   mData[n--] = max;
   maxIndex = treeSize;
   while (tree[maxIndex] != max) {
    maxIndex--;
   }
   tree[maxIndex] = MinValue;
   while (maxIndex > 1) {
    if (maxIndex % 2 == 0) {
     tree[maxIndex / 2] = (tree[maxIndex] > tree[maxIndex + 1] ? tree[maxIndex]
       : tree[maxIndex + 1]);
    } else {
     tree[maxIndex / 2] = (tree[maxIndex] > tree[maxIndex - 1] ? tree[maxIndex]
       : tree[maxIndex - 1]);
    }
    maxIndex /= 2;
   }
  }
  return mData;
 }
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  int array[] = { 38, 62, 35, 77, 55, 14, 35, 98 };
  TreeSelectionSort(array);
  for (int i = 0; i < array.length; i++) {
   System.out.print(array[i] + " ");
  }
  System.out.println("\n");
 }
}

Algorithm analysis:

In tree selection sorting, except for the smallest keyword, the selected smallest keyword all goes through a comparison process from leaf nodes to follow nodes. Since the depth of a complete binary tree containing n leaf nodes is log2n +1, therefore in tree selection sorting, each time a smaller keyword is selected, log2n comparisons are required, so the time complexity is O(nlog2n), and the number of moving records does not exceed the number of comparisons, so the total algorithm time is complex The degree is O(nlog2n). Compared with the simple selection sort algorithm, it reduces the number of comparisons by an order of magnitude and adds n-1 additional storage space to store intermediate comparison results.

Supplement:

Here we introduce the improved algorithm for tree selection sorting, namely the heap sorting algorithm.

Heap sorting makes up for the shortcoming of the tree selection sorting algorithm that takes up a lot of space. When using heap sort, only one record-sized auxiliary space is required.

The algorithm idea is:

Store the keywords of the records to be sorted in the array r[1...n], and r It is regarded as a sequential representation of a complete binary tree. Each node represents a record. The first record r[1] is used as the root of the binary tree. Each of the following records r[2...n] is layered from left to layer. Arranged in right order, the left child of any node r[i] is r[2*i], the right child is r[2*i+1]; the parent is r[[i/2]].

Heap definition: The key value of each node satisfies the following conditions:

r[i].key >= r[2i].key and r[ i].key >= r[2i+1].key (i=1,2,...[i/2])

The complete binary tree that meets the above conditions is called a large root heap; on the contrary, if The key of any node in this complete binary tree is less than or equal to the key of its left child and right child, and the corresponding heap is called a small root heap.

The process of heap sorting mainly needs to solve two problems: the first is to build an initial heap according to the heap definition; the second is to rebuild the heap after removing the largest element to obtain the sub-large element.

Heap sorting is to use the characteristics of the heap to sort the record sequence. The process is as follows:

1. Build a heap for the given sequence;
2. Output the top of the heap; (first element Exchange with the tail element)
3. Rebuild the heap with the remaining elements; (filter the first element)
4. Repeat steps 2 and 3 until all elements are output.

Note: "Filtering" must start from the [n/2]th node and go backwards layer by layer until the root node.

Algorithm analysis:

1. For a heap with a depth of k, the number of keyword comparisons required for "filtering" is at most 2(k-1) ;
2. The heap depth of n keywords is [log2n]+1, and the number of keyword comparisons required to initially build the heap is at most: n* [log2n];
3. Rebuild the heap n- 1 time, the number of keyword comparisons required does not exceed: (n-1)*2 [log2n];

Therefore, in the worst case, the time complexity of heap sort is O(nlog2n ), this is the biggest advantage of heap sort.

[Related recommendations]

1. Detailed tutorial on selection sorting (Selection Sort_java) in Java

2. java data structure Sorting algorithm (2) Merge sort

3. java data structure sorting algorithm (3) Simple selection sort

4. java data structure sorting Algorithm (4) Selection sort

The above is the detailed content of Java data structure sorting algorithm (1) Tree selection sorting. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly obtain entity class variable names to build database query conditions?How to elegantly obtain entity class variable names to build database query conditions?Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list?How to use the Redis cache solution to efficiently realize the requirements of product ranking list?Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

How to safely convert Java objects to arrays?How to safely convert Java objects to arrays?Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How do I convert names to numbers to implement sorting and maintain consistency in groups?How do I convert names to numbers to implement sorting and maintain consistency in groups?Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the default run configuration list of SpringBoot projects in Idea for team members to share?How to set the default run configuration list of SpringBoot projects in Idea for team members to share?Apr 19, 2025 pm 11:24 PM

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor