How to implement merge sort in Java
Implementation code
import java.lang.reflect.Array; import java.util.*; public class MergeSort{ // 我们的算法类不允许产生任何实例 private MergeSort(){} // 将arr[l...mid]和arr[mid+1...r]两部分进行归并 private static void merge(Comparable[] arr, int l, int mid, int r) { Comparable[] aux = Arrays.copyOfRange(arr, l, r+1); // 初始化,i指向左半部分的起始索引位置l;j指向右半部分起始索引位置mid+1 int i = l, j = mid+1; for( int k = l ; k <= r; k ++ ){ if( i > mid ){ // 如果左半部分元素已经全部处理完毕 arr[k] = aux[j-l]; j ++; } else if( j > r ){ // 如果右半部分元素已经全部处理完毕 arr[k] = aux[i-l]; i ++; } else if( aux[i-l].compareTo(aux[j-l]) < 0 ){ // 左半部分所指元素 < 右半部分所指元素 arr[k] = aux[i-l]; i ++; } else{ // 左半部分所指元素 >= 右半部分所指元素 arr[k] = aux[j-l]; j ++; } } } // 递归使用归并排序,对arr[l...r]的范围进行排序 private static void sort(Comparable[] arr, int l, int r, int depth) { System.out.print(repeatCharacters('-', depth*2)); System.out.println("Deal with [ " + l + " , " + r + " ]"); if (l >= r) return; int mid = (l+r)/2; sort(arr, l, mid, depth + 1); sort(arr, mid + 1, r, depth + 1); merge(arr, l, mid, r); } private static String repeatCharacters(char character, int length){ StringBuilder s = new StringBuilder(length); for(int i = 0 ; i < length ; i ++) s.append(character); return s.toString(); } public static void sort(Comparable[] arr){ int n = arr.length; sort(arr, 0, n-1, 0); } // 测试MergeSort public static void main(String[] args) { // Merge Sort是我们学习的第一个O(nlogn)复杂度的算法 // 可以在1秒之内轻松处理100万数量级的数据 // 注意:不要轻易尝试使用SelectionSort, InsertionSort或者BubbleSort处理100万级的数据 // 否则,你就见识了O(n^2)的算法和O(nlogn)算法的本质差异:) // int N = 1000000; // Integer[] arr = SortTestHelper.generateRandomArray(N, 0, 100000); // SortTestHelper.testSort("bobo.algo.MergeSort", arr); Integer[] arr = new Integer[8]; for(int i = 0 ; i < 8 ; i ++) { arr[i] = new Integer(8-i); // arr[i] = 8 -i; } // arr = SortTestHelper.generateRandomArray(50, 1, 50); MergeSort.sort(arr); return; } }
import java.lang.reflect.Method; import java.lang.Class; import java.util.Random; public class SortTestHelper { // SortTestHelper不允许产生任何实例 private SortTestHelper(){} // 生成有n个元素的随机数组,每个元素的随机范围为[rangeL, rangeR] public static Integer[] generateRandomArray(int n, int rangeL, int rangeR) { assert rangeL <= rangeR; Integer[] arr = new Integer[n]; for (int i = 0; i < n; i++) arr[i] = new Integer((int)(Math.random() * (rangeR - rangeL + 1) + rangeL)); return arr; } // 生成一个近乎有序的数组 // 首先生成一个含有[0...n-1]的完全有序数组, 之后随机交换swapTimes对数据 // swapTimes定义了数组的无序程度: // swapTimes == 0 时, 数组完全有序 // swapTimes 越大, 数组越趋向于无序 public static Integer[] generateNearlyOrderedArray(int n, int swapTimes){ Integer[] arr = new Integer[n]; for( int i = 0 ; i < n ; i ++ ) arr[i] = new Integer(i); for( int i = 0 ; i < swapTimes ; i ++ ){ int a = (int)(Math.random() * n); int b = (int)(Math.random() * n); int t = arr[a]; arr[a] = arr[b]; arr[b] = t; } return arr; } // 打印arr数组的所有内容 public static void printArray(Object[] arr) { for (int i = 0; i < arr.length; i++){ System.out.print( arr[i] ); System.out.print( ' ' ); } System.out.println(); return; } // 判断arr数组是否有序 public static boolean isSorted(Comparable[] arr){ for( int i = 0 ; i < arr.length - 1 ; i ++ ) if( arr[i].compareTo(arr[i+1]) > 0 ) return false; return true; } // 测试sortClassName所对应的排序算法排序arr数组所得到结果的正确性和算法运行时间 public static void testSort(String sortClassName, Comparable[] arr){ // 通过Java的反射机制,通过排序的类名,运行排序函数 try{ // 通过sortClassName获得排序函数的Class对象 Class sortClass = Class.forName(sortClassName); // 通过排序函数的Class对象获得排序方法 Method sortMethod = sortClass.getMethod("sort",new Class[]{Comparable[].class}); // 排序参数只有一个,是可比较数组arr Object[] params = new Object[]{arr}; long startTime = System.currentTimeMillis(); // 调用排序函数 sortMethod.invoke(null,params); long endTime = System.currentTimeMillis(); assert isSorted( arr ); System.out.println( sortClass.getSimpleName()+ " : " + (endTime-startTime) + "ms" ); } catch(Exception e){ e.printStackTrace(); } } }
Implementation effect
The above is the detailed content of How to implement merge sort in Java. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Create a WebSocket server endpoint to define the path using @ServerEndpoint, and handle connections, message reception, closing and errors through @OnOpen, @OnMessage, @OnClose and @OnError; 2. Ensure that javax.websocket-api dependencies are introduced during deployment and automatically registered by the container; 3. The Java client obtains WebSocketContainer through the ContainerProvider, calls connectToServer to connect to the server, and receives messages using @ClientEndpoint annotation class; 4. Use the Session getBasicRe

Using SLF4J combined with Logback or Log4j2 is the recommended way to configure logs in Java applications. It introduces API and implementation libraries by adding corresponding Maven dependencies; 2. Get the logger through the LoggerFactory of SLF4J in the code, and write decoupled and efficient log code using parameterized logging methods; 3. Define log output format, level, target (console, file) and package level log control through logback.xml or log4j2.xml configuration files; 4. Optionally enable the configuration file scanning function to achieve dynamic adjustment of log level, and SpringBoot can also be managed through Actuator endpoints; 5. Follow best practices, including

PrepareyourapplicationbyusingMavenorGradletobuildaJARorWARfile,externalizingconfiguration.2.Chooseadeploymentenvironment:runonbaremetal/VMwithjava-jarandsystemd,deployWARonTomcat,containerizewithDocker,orusecloudplatformslikeHeroku.3.Optionally,setup

To effectively protect phpMyAdmin, multiple layers of security measures must be taken. 1. Restrict access through IP, only trusted IP connections are allowed; 2. Modify the default URL path to a name that is not easy to guess; 3. Use strong passwords and create a dedicated MySQL user with minimized permissions, and it is recommended to enable two-factor authentication; 4. Keep the phpMyAdmin version up to fix known vulnerabilities; 5. Strengthen the web server and PHP configuration, disable dangerous functions and restrict file execution; 6. Force HTTPS to encrypt communication to prevent credential leakage; 7. Disable phpMyAdmin when not in use or increase HTTP basic authentication; 8. Regularly monitor logs and configure fail2ban to defend against brute force cracking; 9. Delete setup and

EnsureAutoFillisenabledbychecking"Enablefillhandleandcelldrag-and-drop"inFile>Options>Advanced;2.Correctlyusethefillhandle—thesmallsquareatthebottom-rightoftheselectedcell—draggingwiththeblackpluscursor,notthewhitearrow;3.Unmergecells
![You are not currently using a display attached to an NVIDIA GPU [Fixed]](https://img.php.cn/upload/article/001/431/639/175553352135306.jpg?x-oss-process=image/resize,m_fill,h_207,w_330)
Ifyousee"YouarenotusingadisplayattachedtoanNVIDIAGPU,"ensureyourmonitorisconnectedtotheNVIDIAGPUport,configuredisplaysettingsinNVIDIAControlPanel,updatedriversusingDDUandcleaninstall,andsettheprimaryGPUtodiscreteinBIOS/UEFI.Restartaftereach

TheassertkeywordinJavaisusedtovalidateassumptionsduringdevelopment,throwinganAssertionErroriftheconditionisfalse.2.Ithastwoforms:assertcondition;andassertcondition:message;withthelatterprovidingacustomerrormessage.3.Assertionsaredisabledbydefaultandm

XSLT parameters are a key mechanism for dynamic conversion through external passing values. 1. Use declared parameters and set default values; 2. Pass the actual value from application code (such as C#) through interfaces such as XsltArgumentList; 3. Control conditional processing, localization, data filtering or output format through $paramName reference parameters in the template; 4. Best practices include using meaningful names, providing default values, grouping related parameters, and performing value verification. The rational use of parameters can make XSLT style sheets highly reusable and maintainable, and the same style sheets can produce diversified output results based on different inputs.
