Home Java javaTutorial Detailed explanation of examples of implementation of insertion sort in java

Detailed explanation of examples of implementation of insertion sort in java

May 13, 2017 am 11:02 AM
java insertion sort data structure algorithm

This article mainly introduces the insertion sort of java data structure and algorithm, and analyzes the concept, classification, principle, implementation method and related precautions of java insertion sort in the form of examples. Friends in need can refer to it

The examples in this article describe insertion sorting of java data structures and algorithms. I share it with you for your reference. The details are as follows:

After reviewing, I sorted out the knowledge about sorting in the data structure. I wrote it down because I want to share it with more people. The most important thing is Just make a backup for future reference.

Sort

1. Concept:

A sequence with n records {R1, R2,.......,Rn} (note here: 1,2,n are the sequences in the table below, and the following have the same effect), and the sequence of the corresponding keywords is {K1,K2,.... .....,Kn}. Through sorting, it is required to find an arrangement p1, p2,...pn of the current subscript sequence 1,2,...,n, so that the corresponding keyword satisfies the following non-decreasing ( Non-increasing) relationship, that is: Kp1<=Kp2<=Kpn, thus obtaining a sequence of records ordered by keyword: {Rp1, Rp2,.....,Rpn}.

2. Classification

Sorting can be divided into two categories based on the difference in memory occupied by data during sorting.

Internal sorting: The entire sorting process is completely performed in memory, as follows:

Insertion sorting (direct insertion sorting, half insertion sorting, Hill sorting );

Exchange class sorting (Bubble sort, quick sort);

Selection class sorting (simpleSelection sort, tree selection sort, heap sort);

Merge sort;

Allocation class sort (multi-key Sequence table implementation of word sort, chained radix sort, and radix sort));

External sorting: Because the amount of data to be sorted is too large, the memory cannot accommodate all the data. Sorting requires the use of external storage devices (disk sorting, tape sorting).

3. Stability

Assume that there are multiple records with the same keyword in the sequence to be sorted. Assume Ki=Kj(1<=i<=n,1<=j<=n,i != j), if Ri leads Rj (i.e. i<=j) in the sequence before sorting, we get after sorting If Ri still leads Rj in the sequence, the sorting method used is said to be stable; conversely, when the leading relationship of the same keyword changes during the sorting process, the sorting method used is unstable.

Insertion sort:

Idea: Each time a record to be sorted is inserted into the appropriate position in the previously sorted sub-file according to its key size until all records are inserted. until completed.

Direct insertion sorting:

Algorithm idea: Assume that the records to be sorted are stored in the arrayR[1.. n] in. Initially, R[1] forms an ordered area, and the unordered area is R[2..n]. From i=2 until i=n, ​​R[i] is inserted into the current ordered area R[1..i-1] in sequence, generating an ordered area containing n records.

The code implemented in java is as follows:


package exp_sort;
public class DirectInsertSort {
  public static void DircstSort(int array[]) {
    int j;
    // 循环从第二个数开始,第一个数用做存放待插入的记录
    for (int i = 1; i < array.length; i++) {
      int temp = array[i];
      // 寻找插入位置
      for (j = i; j > 0 && temp < array[j - 1]; j--) {
        array[j] = array[j - 1];
      }
      // 将待插入记录插入到已经排序的序列中
      array[j] = temp;
    }
    for (int i = 0; i < array.length; i++) {
      System.out.print(array[i] + " ");
    }
    System.out.println("\n");
  }
  public static void main(String[] args) {
    // TODO Auto-generated method stub
    int array[] = { 38, 62, 35, 77, 55, 14, 35, 98 };
    DircstSort(array);
  }
}
Copy after login

Algorithm analysis: The best situation is that the record to be sorted itself has been sorted according to the key The words are arranged in order. The worst case is that the records to be sorted are arranged in reverse order according to the keywords; The time complexity is O(N^2) and the space complexity is O(1); This algorithm is a stable sorting algorithm: It is more suitable for situations where the number of records to be sorted is small and basically in order.

Half Insertion Sort:

Algorithm idea: The performance of halved search for ordered tables is better than sequential search.

The algorithm implementation code is as follows:


package exp_sort;
public class BinaryInsertSort {
  public static void sort(int array[]) {
    int temp, low, mid, high;
    for (int i = 1; i < array.length; i++) {
      temp = array[i];
      low = 0;
      high = i -1;
      //确定插入位置
      while (low <= high) {
        mid = (low + high) / 2;
        if (temp < array[mid]) {
          high = mid - 1;
        } else {
          low = mid + 1;
        }
      }
      //记录依次向后移动
      for (int j = i; j >= low + 1; j--) {
        array[j] = array[j-1];
      }
      //插入记录
      array[low] = temp;
    }
    for (int i = 0; i < array.length; i++) {
      System.out.print(array[i] + " ");
    }
    System.out.println("\n");
  }
  public static void main(String[] args) {
    // TODO Auto-generated method stub
    int array[] = {38, 62, 35, 77, 55, 14, 35, 98};
    sort(array);
  }
}
Copy after login

Algorithm analysis: is a stable sorting algorithm, which is significantly less expensive than the direct insertion algorithm The number of comparisons between keywords is reduced, so the speed is faster than the direct insertion sort algorithm , but the number of record moves has not changed, so the time complexity of the half insertion sort algorithm is still O (n^2), is the same as the direct insertion sort algorithm. Additional space O(1).

【Related recommendations】

1. Special recommendation:"php "Programmer's Toolbox" V0.1 version download

2. Java Free Video Tutorial

##3. YMP Online Manual

The above is the detailed content of Detailed explanation of examples of implementation of insertion sort in java. 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)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks 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