search
HomeJavajavaTutorialQuick Sort in Java

Quick Sort in Java

Aug 30, 2024 pm 03:32 PM
java

The following article, Quick Sort in Java, provides an outline for the quick sort algorithm in java. The Quick Sort Algorithm is one of the sorting algorithms which is efficient and similar to that of the merge sort algorithm. This is one of the prevalently used algorithms for real-time sorting purposes. The worst-case time complexity of this algorithm is O(n^2), the average-case time complexity is O(n log n), and the best-case time complexity is O(n log n).

The space complexity if O(n log n), where is n is the size of the input. The process of sorting involves the partitioning of input, recursive iterations and marking a pivotal element for each recursion. The type of sorting in this algorithm involves a comparison of adjacent elements in an iterative manner.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

How Quick Sort Works in Java?

Quick Sort algorithm can be implemented in Java by forming a pseudo code with a sequence of steps designed and followed in an efficient manner.

  • The main principle of the quick sort algorithm that it works is based on the divide and conquer approach and is also an efficient sorting algorithm.
  • The input array is divided into sub-arrays, and the division is based on the pivot element, which is a central element. The sub-arrays on either side of the pivot element are the main areas where the sorting actually occurs.
  • The central pivot element is the base to divide the array into two partitions where the left half of array elements are lesser than the pivot element, and the right half of array elements are greater than the pivot element.
  • Before considering the pivot element, it can be anyone from the elements of an array. This is normally considered the middle one or the first one, or the last one for ease of understanding. The pivot element can be a random one from any of the array elements.
  • In our example, the last element of an array is considered as a pivot element, where the partitioning of sub-arrays starts from the right end of the array.
  • Finally, the pivot element will be in its actual sorted position after the completion of the sorting process, where the main process of sorting lies in the partition logic of the sorting algorithm.
  • The efficiency of the algorithm depends on the size of the sub-arrays and how they are balanced. The more the sub-arrays are unbalanced, the more the time complexity will be, leading to worst-case complexity.
  • The selection of pivot elements in a random manner results in the best time complexity in many cases instead of choosing a particular start, end or middle indexes as the pivot elements.

Examples to Implement Quick Sort in Java

The QuickSort algorithm has been implemented using Java programming language as below, and the output code has been displayed under the code.

  • The code initially takes the input using the method quickSortAlgo() with the array, initial index and final index, i.e., length of the array as the arguments.
  • After calling the quickSortAlgo() method, it checks if the initial index is less than the final index and then calls the arrayPartition() method to get the pivot element value.
  • The partition element contains the logic of arranging the smaller and larger elements based on the element values around the pivot element.
  • After getting the pivot element index after partition method execution, the quickSortAlgo() method is called by itself recursively until all the sub-arrays are partitioned and sorted completely.
  • In the partition logic, the last element is assigned as a pivot element and the first element is compared with the pivot element, i.e. the last one where the elements are swapped based on whether they are smaller or greater.
  • This process of recursion happens until all the elements of an array are partitioned and sorted, where the final result is a combined sorted array.
  • The elements are swapped inside the for-loop iteration only in the case the element is lesser than or equal to the pivot element.
  • After completing the iteration process, the last element is swapped, i.e. the pivot element value is moved to the left side so that the new partitions are made, and the same process repeats in the form of recursion, which results in series of sorting operations on different possible partitions as a formation of sub-arrays out of the given array elements.
  • The below code can be run on any IDE, and the output can be verified by changing the array value in the main(). The main method is used just for the purpose of getting the output in the console. As a part of Java coding standards, the main method can be removed below, and an object can be created, and the below methods can be called by making them non-static.

Code Implementation of Quick Sort Algorithm in Java

Following is a code implementation:

Code:

/*
* Quick Sort algorithm - Divide & Conquer approach
*/
public class QuickSortAlgorithm {
public static void main(String[] args) {
int[] array = { 99, 31, 1, 3, 5, 561, 1, 342, 345, 454 };
quickSortAlgo(array, 0, array.length - 1);
for (int ar : array) {
System.out.print(ar + " ");
}
}
public static int arrayPartition(int[] array, int start, int end) {
int pivot = array[end];
int i = (start - 1);
for (int ele = start; ele 
<p><strong>Output:</strong></p>


<p><img  src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/172500312462961.png?x-oss-process=image/resize,p_40" class="lazy" alt="Quick Sort in Java" ></p>
<h3 id="Conclusion">Conclusion</h3>
<p>The Quick Sort Algorithm is efficient but not much stable as compared to other sorting techniques. The efficiency of quick sort algorithms comes down in the case of a greater number of repeated elements which is a drawback. The space complexity is optimized in this quick sort algorithm.</p>

The above is the detailed content of Quick Sort in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
Is Java Platform Independent if then how?Is Java Platform Independent if then how?May 09, 2025 am 12:11 AM

Java is platform-independent because of its "write once, run everywhere" design philosophy, which relies on Java virtual machines (JVMs) and bytecode. 1) Java code is compiled into bytecode, interpreted by the JVM or compiled on the fly locally. 2) Pay attention to library dependencies, performance differences and environment configuration. 3) Using standard libraries, cross-platform testing and version management is the best practice to ensure platform independence.

The Truth About Java's Platform Independence: Is It Really That Simple?The Truth About Java's Platform Independence: Is It Really That Simple?May 09, 2025 am 12:10 AM

Java'splatformindependenceisnotsimple;itinvolvescomplexities.1)JVMcompatibilitymustbeensuredacrossplatforms.2)Nativelibrariesandsystemcallsneedcarefulhandling.3)Dependenciesandlibrariesrequirecross-platformcompatibility.4)Performanceoptimizationacros

Java Platform Independence: Advantages for web applicationsJava Platform Independence: Advantages for web applicationsMay 09, 2025 am 12:08 AM

Java'splatformindependencebenefitswebapplicationsbyallowingcodetorunonanysystemwithaJVM,simplifyingdeploymentandscaling.Itenables:1)easydeploymentacrossdifferentservers,2)seamlessscalingacrosscloudplatforms,and3)consistentdevelopmenttodeploymentproce

JVM Explained: A Comprehensive Guide to the Java Virtual MachineJVM Explained: A Comprehensive Guide to the Java Virtual MachineMay 09, 2025 am 12:04 AM

TheJVMistheruntimeenvironmentforexecutingJavabytecode,crucialforJava's"writeonce,runanywhere"capability.Itmanagesmemory,executesthreads,andensuressecurity,makingitessentialforJavadeveloperstounderstandforefficientandrobustapplicationdevelop

Key Features of Java: Why It Remains a Top Programming LanguageKey Features of Java: Why It Remains a Top Programming LanguageMay 09, 2025 am 12:04 AM

Javaremainsatopchoicefordevelopersduetoitsplatformindependence,object-orienteddesign,strongtyping,automaticmemorymanagement,andcomprehensivestandardlibrary.ThesefeaturesmakeJavaversatileandpowerful,suitableforawiderangeofapplications,despitesomechall

Java Platform Independence: What does it mean for developers?Java Platform Independence: What does it mean for developers?May 08, 2025 am 12:27 AM

Java'splatformindependencemeansdeveloperscanwritecodeonceandrunitonanydevicewithoutrecompiling.ThisisachievedthroughtheJavaVirtualMachine(JVM),whichtranslatesbytecodeintomachine-specificinstructions,allowinguniversalcompatibilityacrossplatforms.Howev

How to set up JVM for first usage?How to set up JVM for first usage?May 08, 2025 am 12:21 AM

To set up the JVM, you need to follow the following steps: 1) Download and install the JDK, 2) Set environment variables, 3) Verify the installation, 4) Set the IDE, 5) Test the runner program. Setting up a JVM is not just about making it work, it also involves optimizing memory allocation, garbage collection, performance tuning, and error handling to ensure optimal operation.

How can I check Java platform independence for my product?How can I check Java platform independence for my product?May 08, 2025 am 12:12 AM

ToensureJavaplatformindependence,followthesesteps:1)CompileandrunyourapplicationonmultipleplatformsusingdifferentOSandJVMversions.2)UtilizeCI/CDpipelineslikeJenkinsorGitHubActionsforautomatedcross-platformtesting.3)Usecross-platformtestingframeworkss

See all articles

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

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)