Home Java javaTutorial Java data structure sorting algorithm (1) Tree selection sorting

Java data structure sorting algorithm (1) Tree selection sorting

May 31, 2017 am 09:27 AM
java data structure

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");
 }
}
Copy after login

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 of this Website
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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

How to Run Your First Spring Boot Application in Spring Tool Suite? How to Run Your First Spring Boot Application in Spring Tool Suite? Feb 07, 2025 pm 12:11 PM

Spring Boot simplifies the creation of robust, scalable, and production-ready Java applications, revolutionizing Java development. Its "convention over configuration" approach, inherent to the Spring ecosystem, minimizes manual setup, allo

See all articles