Home Java javaTutorial JAVA simple selection sorting algorithm principle and implementation

JAVA simple selection sorting algorithm principle and implementation

Jan 17, 2017 pm 01:08 PM
java Sorting Algorithm

Simple selection sorting: (select the smallest value, put it first, and then move the first value backward, and so on) Compare the first value with each subsequent one one by one, and put the smallest one at the top each time. The bits are pushed backward (that is, the first bit just selected is the minimum value and will no longer participate in the comparison, and the number of comparisons is reduced by 1)

Complexity: The number of operations required to move the record is less 0--3 (n-1), regardless of the initial arrangement of the records, the number of comparisons required between keywords is the same, which is n(n-1)/2, and the total time complexity is O(n2);
space Complexity O(1)

Algorithm improvement: Every comparison is to put the smallest value first, so you can compare it to the end, find the smallest value, and put it directly in the first place. Eliminate meaningless swap and move operations. You can also change the direction, and compare the last bit with each previous one, making the maximum value sink to the bottom each time, and the last bit advances forward.

JAVA source code:

 public static void selectSort(Date[] days) {
  int min;
  Date temp;
  for (int i = 0; i < days.length; i++) {
   min = i;
   for (int j = min + 1; j < days.length; j++) {
    if (days[min].compare(days[j]) > 0) {
     min = j;
    }
   }
   if (min != i) {
    temp = days[i];
    days[i] = days[min];
    days[min] = temp;
   }
  }
 }
class Date {
 int year, month, day;
 Date(int y, int m, int d) {
  year = y;
  month = m;
  day = d;
 }
 public int compare(Date date) {
  return year > date.year ? 1 : year < date.year ? -1
    : month > date.month ? 1 : month < date.month ? -1
      : day > date.day ? 1 : day < date.day ? -1 : 0;
 }
 public void print() {
  System.out.println(year + " " + month + " " + day);
 }
}
Copy after login

Simple Selection Sort:

Simple Selection Sort is similar to Bubble Sort (Bubble Sort), each time it will be in the remaining Select the highest value from the set of elements below and fill it into the current position. The only difference is that bubble sort will exchange the position of the element every time it finds that it is less than (or greater than) the current value, while simple selection sort selects the highest value among the remaining elements and exchanges data with the current position.

For example, for the element set R={37, 40, 38, 42, 461, 5, 7, 9, 12}

In the first sorting: 37 is directly exchanged with 5, Form a new sequence R1={5,40,38,42,461,37,7,9,12}
In the second sorting: 40 is directly exchanged with 7 to form a new sequence R2={5,7, 38,42,461,37,40,9,12}

and so on until the last element (note: in the second pass of sorting, 38 is smaller than 42, but they do not exchange data).

The following is a Java implementation version of simple selection sorting:

  public static void selectionSort(int[] data) {
  if (data == null || data.length <= 1)
  return;
  int i, j, value, minPos, len = data.length;
  int outer = len - 1, tmp;
  for (i = 0; i < outer; i++) {
  value = data[i];
  minPos = -1;
  for (j = i + 1; j < len; j++) {
  if (data[j] < value) {
  minPos = j;
  value = data[j];
  }
  }
  if (minPos != -1) {
  tmp = data[i];
  data[i] = value;
  data[minPos] = tmp;
  }
  //            for (int k = 0; k < len; k++) {
  //                System.out.print(data[k] + " , ");
  //            }
  //            System.out.println();
  }
  }
  public static void main(String[] args) {
  int[] coll = {
  37, 40, 38, 42, 461, 5,  7, 9, 12
  };
  selectionSort(coll);
  for (int i = 0; i < coll.length; i++) {
  System.out.print(coll[i] + " , ");
  }
  }
Copy after login

Tree Selection Sort (Tree Selection Sort)
The tree selection sorting algorithm is typical of simple selection sorting. Algorithm for exchanging space for time. The idea is to treat the sorted N elements, construct relatively small (n+1)/2 numbers, and then construct relatively small [n+1]/4 numbers until there is only one element. Constructed into a complete binary tree.
When sorting, that element is the smallest, take out the smallest element, replace the element with the "maximum value", and then adjust the complete binary tree.
The following is a Java implementation version of tree selection sorting:

  public static void treeSelectionSort(int[] data) {
  if (data == null || data.length <= 1)
  return;
  int len = data.length , low = 0 , i , j;
  // add Auxiliary Space
  int[] tmp = new int[2*len -1];
  int tSize = tmp.length;
  //construct a tree
  for(i =len-1 , j=tmp.length-1;i >=0 ;i--,j--){
  tmp[j]=data[i];
  }
  for(i = tSize -1 ; i > 0 ; i-=2){
  tmp[(i-1)/2] = tmp[i] > tmp[i-1]? tmp[i-1]:tmp[i];
  }
  //end
  //remove the minimum node.
  while(low < len){
  data[low++] = tmp[0];
  for(j=tSize-1;tmp[j]!=tmp[0];j--);
  tmp[j] = Integer.MAX_VALUE;
  while(j > 0){
  if(j%2 == 0){  //如果是右节点
  tmp[(j-1)/2] = tmp[j] > tmp[j-1]?tmp[j-1]:tmp[j];
  j = (j-1)/2;
  }else{  //如果是左节点
  tmp[j/2]=tmp[j] > tmp[j+1]? tmp[j+1]:tmp[j];
  j = j/2;
  }
  }
  }
  }
Copy after login

When constructing a complete binary tree, a set of N elements requires 2*N -1 auxiliary space.
Code:

  while(j > 0){
  if(j%2 == 0){  //如果是右节点
  tmp[(j-1)/2] = tmp[j] > tmp[j-1]?tmp[j-1]:tmp[j];
  j = (j-1)/2;
  }else{  //如果是左节点
  tmp[j/2]=tmp[j] > tmp[j+1]? tmp[j+1]:tmp[j];
  j = j/2;
  }
  }
Copy after login

implements recursive construction of the minimum value in the new set.

For more articles related to the principle and implementation of JAVA simple selection sorting algorithm, please pay attention to 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

Video Face Swap

Video Face Swap

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

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)

Hot Topics

Java Tutorial
1654
14
PHP Tutorial
1252
29
C# Tutorial
1225
24
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

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

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

PHP's Impact: Web Development and Beyond PHP's Impact: Web Development and Beyond Apr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP: The Foundation of Many Websites PHP: The Foundation of Many Websites Apr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

See all articles