In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces "what sort algorithms does Java have". In daily operation, I believe many people have doubts about what sort algorithms Java has. The editor consulted all kinds of data and sorted out simple and easy-to-use operation methods. I hope it will be helpful for you to answer the doubts about "what sort algorithms Java has". Next, please follow the editor to study!
Introduction to Bubble sorting
Bubble sort (Bubble Sort), also known as bubble sort or bubble sort.
It is a relatively simple sorting algorithm. It traverses several secondary sorted sequences, and each time, it compares the size of two adjacent numbers from the back to the back, and if the former is larger than the latter, swap their positions. In this way, after a traversal, the largest element is at the end of the sequence! After traversing again in the same way, the second largest element is arranged before the largest element. Repeat this until the entire sequence is in order!
Bubble sort picture and text description
/ * * a-- Array to be sorted * n-- length of the array * / public static void bubbleSort (int [] a, int n) {int iMagi j; for (iLeg1; I > 0; iMub -) {/ / put the largest data in a [0. I] at the end of for (jong0; j [juni1]) {/ / exchange aj [j] and a[ j + 1] int tmp = a [j]; a [j] = a [job1] A [jacks 1] = tmp;}
Run:
Int [] a = {20, 40, 30, 10, 60, 50, 70); String aa = "Bubble sorting"; bubbleSort (arect a. Length); System.out.print (aa); for (int d: a) {System.out.print (d + ",");}
Introduction to Quick sort
Quick sorting (Quick Sort) uses the divide and conquer strategy.
Its basic idea is to select a benchmark number and divide the sorted data into two independent parts through a sort; all the data in one part is smaller than all the data in the other part. Then, according to this method, the two parts of data are quickly sorted respectively, and the whole sorting process can be carried out recursively, so that the whole data becomes an ordered sequence.
Quick sort process:
Pick a base value from the sequence. Place all those smaller than the datum in front of the datum, and all those larger than the datum behind the datum (the same number can go to either side); after the partition exits, the datum is in the middle of the series. Sort the subseries before the base value and the subseries after the base value recursively. Introduction of picture and text
Code implementation:
/ * * Parameter description: * a-the array to be sorted * l-the left boundary of the array (for example, sorting from the starting position) * r-the right boundary of the array (for example, sorting to the end of the array, then r=a.length-1) * / public static void quickSort (int [] a, int l, int r) {if (l)
< r) { int i,j,x; i = l; j = r; x = a[i]; while (i < j) { while(i < j && a[j] >X) JMMI; / / find the first number if (I) less than x from right to left
< j) a[i++] = a[j]; while(i < j && a[i] < x) i++; // 从左向右找第一个大于x的数 if(i < j) a[j--] = a[i]; } a[i] = x; quickSort(a, l, i-1); /* 递归调用 */ quickSort(a, i+1, r); /* 递归调用 */ } } 运行: String aa = "快速排序"; quickSort(a,0,a.length-1); System.out.print(aa); for (int d : a) { System.out.print(d+","); } 直接插入排序介绍 直接插入排序(Straight Insertion Sort)的基本思想是:把n个待排序的元素看成为一个有序表和一个无序表。开始时有序表中只包含1个元素,无序表中包含有n-1个元素,排序过程中每次从无序表中取出第一个元素,将它插入到有序表中的适当位置,使之成为新的有序表,重复n-1次可完成排序过程。 直接插入排序图文说明 代码实现: /** * @param * a -- 待排序的数组 * n -- 数组的长度 */ public static void insertSort(int[] a, int n) { int i, j, k; for (i = 1; i < n; i++) { //为a[i]在前面的a[0...i-1]有序区间中找一个合适的位置 for (j = i - 1; j >= 0; jMui -) if (a [j]
< a[i]) break; //如找到了一个合适的位置 if (j != i - 1) { //将比a[i]大的数据向后移 int temp = a[i]; for (k = i - 1; k >A [k + 1] = a [k]; / / put a [I] in the correct position a [k + 1] = temp;}
It runs like bubbling.
Hill sort:
Shell sort, also known as reduced incremental sort, is an insert sort. It is a powerful enhanced version of the direct insertion sorting algorithm. This method is named after DL.Shell proposed in 1959.
The basic idea of Hill sorting is:
The records are grouped according to the step size gap, and each group of records is sorted by direct insertion sorting method.
With the gradual decrease of the step size, the divided group contains more and more records. when the value of the step size is reduced to 1, the whole data are combined into a group to form a set of ordered records, and the sorting is completed.
Let's take a closer look at this process through the illustration.
In the picture above:
Initially, there is an unordered sequence of size 10.
In the first sort, we might as well set gap1 = N / 2 = 5, that is, elements with a distance of 5 form a group, which can be divided into five groups. Next, sort each group by inserting the sort directly.
In the second sort, we cut the last gap by half, that is, gap2 = gap1 / 2 = 2 (take an integer). In this way, elements with a distance of 2 are grouped together and can be divided into two groups. Sort each group according to the method of directly inserting sort.
In the third sort, reduce the gap by half again, that is, gap3 = gap2 / 2 = 1. In this way, elements with a distance of 1 form a group, that is, there is only one group. Sort each group according to the method of directly inserting sort. At this point, the sorting is over.
It should be noted that there are two elements 5 and 5 with equal values in the figure. We can clearly see that during the sorting process, the positions of the two elements are exchanged.
Therefore, Hill sorting is an unstable algorithm.
Code implementation:
/ * * Hill sort * @ param list * / public static void shellSort (int [] a) {int gap = a.length / 2; while (1 = 0 & & temp
< a[j]; j = j - gap) { a[j + gap] = a[j]; } a[j + gap] = temp; } System.out.format("gap = %d:\t", gap); printAll(a); gap = gap / 2; // 减小增量 } } // 打印完整序列 public static void printAll(int[] a) { for (int value : a) { System.out.print(value + "\t"); } System.out.println(); } 运行参考冒泡、、、、、 拓扑排序介绍 拓扑排序(Topological Order)是指,将一个有向无环图(Directed Acyclic Graph简称DAG)进行排序进而得到一个有序的线性序列。 这样说,可能理解起来比较抽象。下面通过简单的例子进行说明! 例如,一个项目包括A、B、C、D四个子部分来完成,并且A依赖于B和D,C依赖于D。现在要制定一个计划,写出A、B、C、D的执行顺序。这时,就可以利用到拓扑排序,它就是用来确定事物发生的顺序的。 在拓扑排序中,如果存在一条从顶点A到顶点B的路径,那么在排序结果中B出现在A的后面。 拓扑排序的算法图解 拓扑排序算法的基本步骤: 1. 构造一个队列Q(queue) 和 拓扑排序的结果队列T(topological); 2. 把所有没有依赖顶点的节点放入Q; 3. 当Q还有顶点的时候,执行下面步骤: 3.1 从Q中取出一个顶点n(将n从Q中删掉),并放入T(将n加入到结果集中); 3.2 对n每一个邻接点m(n是起点,m是终点); 3.2.1 去掉边; 3.2.2 如果m没有依赖顶点,则把m放入Q; 注:顶点A没有依赖顶点,是指不存在以A为终点的边。 以上图为例,来对拓扑排序进行演示。 第1步:将B和C加入到排序结果中。 顶点B和顶点C都是没有依赖顶点,因此将C和C加入到结果集T中。假设ABCDEFG按顺序存储,因此先访问B,再访问C。访问B之后,去掉边和,并将A和D加入到队列Q中。同样的,去掉边和,并将F和G加入到Q中。 将B加入到排序结果中,然后去掉边和;此时,由于A和D没有依赖顶点,因此并将A和D加入到队列Q中。 将C加入到排序结果中,然后去掉边和;此时,由于F有依赖顶点D,G有依赖顶点A,因此不对F和G进行处理。 第2步:将A,D依次加入到排序结果中。 第1步访问之后,A,D都是没有依赖顶点的,根据存储顺序,先访问A,然后访问D。访问之后,删除顶点A和顶点D的出边。 第3步:将E,F,G依次加入到排序结果中。 因此访问顺序是:B ->C-> A-> D-> E-> F-> G
Code description of topological sort
Topological sorting is the sort of directed undirected graph. The topological sorting is illustrated by the directed graph implemented by the adjacency table.
1. Basic definition
The vertex private class ENode of the linked list corresponding to the table in the public class ListDG {int ivex; / / the position of the vertex pointed to by the edge ENode nextEdge; / / the pointer to the next arc} / / the vertex in the adjacency table private class VNode {char data; / / vertex information ENode firstEdge; / / points to the first arc attached to the vertex; private VNode [] mVexs; / / vertex array.}
ListDG is the corresponding structure of the adjacency table. MVexs is an one-dimensional array that holds vertex information. VNode is the structure corresponding to the vertices of the adjacency table. Data is the data contained in a vertex, and firstEdge is the header pointer to the linked list contained by that vertex. ENode is the structure corresponding to the nodes of the linked list contained by the vertices of the adjacency table. Ivex is the index of the vertex corresponding to that node in vexs, while nextEdge points to the next node.
two。 Topological sorting
/ * * topological sorting * * return value: *-1-failed (due to insufficient memory, etc.) * 0-successfully sorted, and enter the result * 1-failed (the directed graph is cyclic) * / public int topologicalSort () {int index = 0; int num = mVexs.size (); int [] ins; / / entry degree array char [] tops / / an array of topological sorting results, recording the sorted sequence number of each node. Queue queue; / / Auxiliary queue ins = new int [num]; tops = new char [num]; queue = new LinkedList (); / / count the number of degrees per vertex for (int I = 0; I < num; ifold +) {ENode node = mVexs.get (I) .firstEdge; while (node! = null) {ins [node.ivex] +; node = node.nextEdge;}} / / queue for (int I = 0; I < num) I + +) if (ins [I] = = 0) queue.offer (I); / in queue while (! queue.isEmpty ()) {/ / queue is not empty int j = queue.poll () .intValue (); / / out of queue. J is the sequence number of the vertex tops [index++] = mVexs.get (j) .data; / / add the vertex to the tops, and tops is the sort result ENode node = mVexs.get (j) .firstEdge; / / get the outbound queue starting from the vertex / / subtract 1 from the node associated with "node"; / / if the node is 0 after minus 1, the node is added to the queue. While (node! = null) {/ / subtracts the entry of the node (serial number node.ivex) by 1. Ins [node.ivex]--; / / if the node's enrollment is 0, the node is "queued" if (ins [node.ivex] = = 0) queue.offer (node.ivex); / / queued node = node.nextEdge;}} if (index! = num) {System.out.printf ("Graph has a cycle\ n"); return 1;} / / print the topological sorting result System.out.printf ("= = TopSort:"); for (int I = 0) I < num; I + +) System.out.printf ("% c", tops [I]); System.out.printf ("\ n"); return 0;}
Description:
The purpose of queue is to store vertices that do not depend on vertices. It corresponds to the Q mentioned earlier. The purpose of tops is to store the sort results. It corresponds to the T mentioned earlier.
Merge and sort
Basic thought
Merging sorting (MERGE-SORT) is a sorting method based on the idea of merging. The algorithm adopts the classical pide-and-conquer strategy (pide divides the problem into some small problems and then recursively solves them, while the conquer stage "patches" the answers obtained in different stages, that is, divide and conquer).
divide and rule
You can see that this structure is very much like a complete binary tree, and the merge sorting in this paper is implemented recursively (or iteratively). Stages can be understood as the process of recursively disassembling the molecular sequence, and the recursive depth is log2n.
Merge adjacent ordered subsequences
Let's take a look at the treatment phase, we need to merge two ordered subsequences into an ordered sequence, such as the last one in the figure above. To merge the two ordered subsequences, [4pc5re7-8] and [1pd2-3-pd6] into the final sequence [1-dint-2-4-4-5-6-pr-7p8], let's take a look at the implementation steps.
Code implementation
Package sortdemo; import java.util.Arrays; / * Created by chengxiao on 2016/12/8.*/public class MergeSort {public static void main (String [] args) {int [] arr = {9 int [] temp = new int [arr.length]; sort (arr); System.out.println (Arrays.toString (arr));} public static void sort [] arr) {int [] temp = new int [arr.length] / / build a temporary array whose length is equal to the length of the original array before sorting, / / avoid frequently opening space sort (arr,0,arr.length-1,temp) in recursion;} private static void sort (int [] arr,int left,int right,int [] temp) {if (left)
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.