Quick Sort Algorithm - GeeksforGeeks (2024)

Last Updated : 28 Jun, 2024

Improve

Improve

Like Article

Like

Save

QuickSort is a sorting algorithm based on the Divide and Conquer algorithm that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array.

How does QuickSort work?

The key process in quickSort is a partition() . The target of partitions is to place the pivot (any element can be chosen to be a pivot) at its correct position in the sorted array and put all smaller elements to the left of the pivot, and all greater elements to the right of the pivot.

Partition is done recursively on each side of the pivot after the pivot is placed in its correct position and this finally sorts the array.

Quick Sort Algorithm - GeeksforGeeks (1)

How Quicksort works

Choice of Pivot:

There are many different choices for picking pivots.

  • Always pick the first element as a pivot .
  • Always pick the last element as a pivot (implemented below)
  • Pick a random element as a pivot .
  • Pick the middle as the pivot.

Partition Algorithm:

The logic is simple, we start from the leftmost element and keep track of the index of smaller (or equal) elements as i . While traversing, if we find a smaller element, we swap the current element with arr[i]. Otherwise, we ignore the current element.

Let us understand the working of partition and the Quick Sort algorithm with the help of the following example:

Consider: arr[] = {10, 80, 30, 90, 40}.

  • Compare 10 with the pivot and as it is less than pivot arrange it accrodingly.

Quick Sort Algorithm - GeeksforGeeks (2)

Partition in QuickSort: Compare pivot with 10

  • Compare 80 with the pivot. It is greater than pivot.

Quick Sort Algorithm - GeeksforGeeks (3)

Partition in QuickSort: Compare pivot with 80

  • Compare 30 with pivot. It is less than pivot so arrange it accordingly.

Quick Sort Algorithm - GeeksforGeeks (4)

Partition in QuickSort: Compare pivot with 30

  • Compare 90 with the pivot. It is greater than the pivot.

Quick Sort Algorithm - GeeksforGeeks (5)

Partition in QuickSort: Compare pivot with 90

  • Arrange the pivot in its correct position.

Quick Sort Algorithm - GeeksforGeeks (6)

Partition in QuickSort: Place pivot in its correct position

Illustration of Quicksort:

As the partition process is done recursively, it keeps on putting the pivot in its actual position in the sorted array. Repeatedly putting pivots in their actual position makes the array sorted.

Follow the below images to understand how the recursive implementation of the partition algorithm helps to sort the array.

  • Initial partition on the main array:

Quick Sort Algorithm - GeeksforGeeks (7)

Quicksort: Performing the partition

  • Partitioning of the subarrays:

Quick Sort Algorithm - GeeksforGeeks (8)

Quicksort: Performing the partition

Quick Sort is a crucial algorithm in the industry, but there are other sorting algorithms that may be more optimal in different cases. To gain a deeper understanding of sorting and other essential algorithms, check out our course Tech Interview 101 – From DSA to System Design . This course covers almost every standard algorithm and more.

Code implementation of the Quick Sort:

C++
#include <bits/stdc++.h>using namespace std;int partition(int arr[],int low,int high){ //choose the pivot  int pivot=arr[high]; //Index of smaller element and Indicate //the right position of pivot found so far int i=(low-1);  for(int j=low;j<=high-1;j++) { //If current element is smaller than the pivot if(arr[j]<pivot) { //Increment index of smaller element i++; swap(arr[i],arr[j]); } } swap(arr[i+1],arr[high]); return (i+1);}// The Quicksort function Implement void quickSort(int arr[],int low,int high){ // when low is less than high if(low<high) { // pi is the partition return index of pivot  int pi=partition(arr,low,high);  //Recursion Call //smaller element than pivot goes left and //higher element goes right quickSort(arr,low,pi-1); quickSort(arr,pi+1,high); }}  int main() { int arr[]={10,7,8,9,1,5}; int n=sizeof(arr)/sizeof(arr[0]); // Function call quickSort(arr,0,n-1); //Print the sorted array cout<<"Sorted Array\n"; for(int i=0;i<n;i++) { cout<<arr[i]<<" "; } return 0;}// This Code is Contributed By Diwakar Jha
C
// C program for QuickSort#include <stdio.h>// Utility function to swap tp integersvoid swap(int* p1, int* p2){ int temp; temp = *p1; *p1 = *p2; *p2 = temp;}int partition(int arr[], int low, int high){ // choose the pivot int pivot = arr[high]; // Index of smaller element and Indicate // the right position of pivot found so far int i = (low - 1); for (int j = low; j <= high - 1; j++) { // If current element is smaller than the pivot if (arr[j] < pivot) { // Increment index of smaller element i++; swap(&arr[i], &arr[j]); } } swap(&arr[i + 1], &arr[high]); return (i + 1);}// The Quicksort function Implementvoid quickSort(int arr[], int low, int high){ // when low is less than high if (low < high) { // pi is the partition return index of pivot int pi = partition(arr, low, high); // Recursion Call // smaller element than pivot goes left and // higher element goes right quickSort(arr, low, pi - 1); quickSort(arr, pi + 1, high); }}int main(){ int arr[] = { 10, 7, 8, 9, 1, 5 }; int n = sizeof(arr) / sizeof(arr[0]);  // Function call quickSort(arr, 0, n - 1);  // Print the sorted array printf("Sorted Array\n"); for (int i = 0; i < n; i++) { printf("%d ", arr[i]); } return 0;}// This Code is Contributed By Diwakar Jha
Java
// Java implementation of QuickSortimport java.io.*;class GFG { // A utility function to swap two elements static void swap(int[] arr, int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } // This function takes last element as pivot, // places the pivot element at its correct position // in sorted array, and places all smaller to left // of pivot and all greater elements to right of pivot static int partition(int[] arr, int low, int high) { // Choosing the pivot int pivot = arr[high]; // Index of smaller element and indicates // the right position of pivot found so far int i = (low - 1); for (int j = low; j <= high - 1; j++) { // If current element is smaller than the pivot if (arr[j] < pivot) { // Increment index of smaller element i++; swap(arr, i, j); } } swap(arr, i + 1, high); return (i + 1); } // The main function that implements QuickSort // arr[] --> Array to be sorted, // low --> Starting index, // high --> Ending index static void quickSort(int[] arr, int low, int high) { if (low < high) { // pi is partitioning index, arr[p] // is now at right place int pi = partition(arr, low, high); // Separately sort elements before // partition and after partition quickSort(arr, low, pi - 1); quickSort(arr, pi + 1, high); } } // To print sorted array public static void printArr(int[] arr) { for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); } } // Driver Code public static void main(String[] args) { int[] arr = { 10, 7, 8, 9, 1, 5 }; int N = arr.length; // Function call quickSort(arr, 0, N - 1); System.out.println("Sorted array:"); printArr(arr); }}// This code is contributed by Ayush Choudhary// Improved by Ajay Virmoti
Python
# Python3 implementation of QuickSort# Function to find the partition positiondef partition(array, low, high): # Choose the rightmost element as pivot pivot = array[high] # Pointer for greater element i = low - 1 # Traverse through all elements # compare each element with pivot for j in range(low, high): if array[j] <= pivot: # If element smaller than pivot is found # swap it with the greater element pointed by i i = i + 1 # Swapping element at i with element at j (array[i], array[j]) = (array[j], array[i]) # Swap the pivot element with # the greater element specified by i (array[i + 1], array[high]) = (array[high], array[i + 1]) # Return the position from where partition is done return i + 1# Function to perform quicksortdef quicksort(array, low, high): if low < high: # Find pivot element such that # element smaller than pivot are on the left # element greater than pivot are on the right pi = partition(array, low, high) # Recursive call on the left of pivot quicksort(array, low, pi - 1) # Recursive call on the right of pivot quicksort(array, pi + 1, high)# Driver codeif __name__ == '__main__': array = [10, 7, 8, 9, 1, 5] N = len(array) # Function call quicksort(array, 0, N - 1) print('Sorted array:') for x in array: print(x, end=" ")# This code is contributed by Adnan Aliakbar
C#
// C# implementation of QuickSortusing System;class GFG { // A utility function to swap two elements static void swap(int[] arr, int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } // This function takes last element as pivot, // places the pivot element at its correct position // in sorted array, and places all smaller to left // of pivot and all greater elements to right of pivot static int partition(int[] arr, int low, int high) { // Choosing the pivot int pivot = arr[high]; // Index of smaller element and indicates // the right position of pivot found so far int i = (low - 1); for (int j = low; j <= high - 1; j++) { // If current element is smaller than the pivot if (arr[j] < pivot) { // Increment index of smaller element i++; swap(arr, i, j); } } swap(arr, i + 1, high); return (i + 1); } // The main function that implements QuickSort // arr[] --> Array to be sorted, // low --> Starting index, // high --> Ending index static void quickSort(int[] arr, int low, int high) { if (low < high) { // pi is partitioning index, arr[p] // is now at right place int pi = partition(arr, low, high); // Separately sort elements before // and after partition index quickSort(arr, low, pi - 1); quickSort(arr, pi + 1, high); } } // Driver Code public static void Main() { int[] arr = { 10, 7, 8, 9, 1, 5 }; int N = arr.Length; // Function call quickSort(arr, 0, N - 1); Console.WriteLine("Sorted array:"); for (int i = 0; i < N; i++) Console.Write(arr[i] + " "); }}// This code is contributed by gfgking
JavaScript
// Function to partition the array and return the partition indexfunction partition(arr, low, high) { // Choosing the pivot let pivot = arr[high];  // Index of smaller element and indicates the right position of pivot found so far let i = low - 1;  for (let j = low; j <= high - 1; j++) { // If current element is smaller than the pivot if (arr[j] < pivot) { // Increment index of smaller element i++; [arr[i], arr[j]] = [arr[j], arr[i]]; // Swap elements } }  [arr[i + 1], arr[high]] = [arr[high], arr[i + 1]]; // Swap pivot to its correct position return i + 1; // Return the partition index}// The main function that implements QuickSortfunction quickSort(arr, low, high) { if (low < high) { // pi is the partitioning index, arr[pi] is now at the right place let pi = partition(arr, low, high);  // Separately sort elements before partition and after partition quickSort(arr, low, pi - 1); quickSort(arr, pi + 1, high); }}// Driver codelet arr = [10, 7, 8, 9, 1, 5];let N = arr.length;// Function callquickSort(arr, 0, N - 1);console.log("Sorted array:");console.log(arr.join(" "));
PHP
<?php // code?><?php // This Function takes place last element as pivot // Place the pivot as correct position // In Sorted Array, and places all smaller to left // of pivot and all greater element to its right of pivot function partition(&$arr,$low,$high) { // Choose the Pivot Element $pivot= $arr[$high]; // Index of smaller element and indicates // The right position of pivot $i=($low-1); for($j=$low;$j<=$high-1;$j++) { if($arr[$j]<$pivot) { // Increment index of smaller element $i++; list($arr[$i],$arr[$j])=array($arr[$j],$arr[$i]); } } // Pivot element as correct position list($arr[$i+1],$arr[$high])=array($arr[$high],$arr[$i+1]); return ($i+1); }// The main function that implement as QuickSort// arr[]:- Array to be sorted// low:- Starting Index//high:- Ending Indexfunction quickSort(&$arr,$low,$high){ if($low<$high) { // pi is partition $pi= partition($arr,$low,$high); // Sort the array // Before the partition of Element quickSort($arr,$low,$pi-1); // After the partition Element quickSort($arr,$pi+1,$high); }}// Driver Code$arr= array(10,7,8,9,1,5);$N=count($arr);// Function CallquickSort($arr,0,$N-1);echo "Sorted Array:\n";for($i=0;$i<$N;$i++){ echo $arr[$i]. " ";} //This code is contributed by Diwakar Jha

Output

Sorted Array1 5 7 8 9 10 

Complexity Analysis of Quick Sort :

Time Complexity:

  • Best Case : Ω (N log (N))
    The best-case scenario for quicksort occur when the pivot chosen at the each step divides the array into roughly equal halves.
    In this case, the algorithm will make balanced partitions, leading to efficient Sorting.
  • Average Case: θ( N log (N))
    Quicksort’s average-case performance is usually very good in practice, making it one of the fastest sorting Algorithm.
  • Worst Case: O(N2)
    The worst-case Scenario for Quicksort occur when the pivot at each step consistently results in highly unbalanced partitions. When the array is already sorted and the pivot is always chosen as the smallest or largest element. To mitigate the worst-case Scenario, various techniques are used such as choosing a good pivot (e.g., median of three) and using Randomized algorithm (Randomized Quicksort ) to shuffle the element before sorting.
  • Auxiliary Space: O(1), if we don’t consider the recursive stack space. If we consider the recursive stack space then, in the worst case quicksort could make O ( N ).

Advantages of Quick Sort:

  • It is a divide-and-conquer algorithm that makes it easier to solve problems.
  • It is efficient on large data sets.
  • It has a low overhead, as it only requires a small amount of memory to function.

Disadvantages of Quick Sort:

  • It has a worst-case time complexity of O(N 2 ), which occurs when the pivot is chosen poorly.
  • It is not a good choice for small data sets.
  • It is not a stable sort, meaning that if two elements have the same key, their relative order will not be preserved in the sorted output in case of quick sort, because here we are swapping elements according to the pivot’s position (without considering their original positions).


`; tags.map((tag)=>{ let tag_url = `videos/${getTermType(tag['term_id__term_type'])}/${tag['term_id__slug']}/`; tagContent+=``+ tag['term_id__term_name'] +``; }); tagContent+=`
`; return tagContent; } //function to create related videos cards function articlePagevideoCard(poster_src="", title="", description="", video_link, index, tags=[], duration=0){ let card = `

${secondsToHms(duration)}

${title}
${showLessRelatedVideoDes(htmlToText(description))} ... Read More

${getTagsString(tags)}

`; return card; } //function to set related videos content function getvideosContent(limit=3){ videos_content = ""; var total_videos = Math.min(videos.length, limit); for(let i=0;i

'; } else{ let view_all_url = `${GFG_SITE_URL}videos/`; videos_content+=`

View All

`; } // videos_content+= '

'; } } return videos_content; } //function to show main video content with related videos content async function showMainVideoContent(main_video, course_link){ //Load main video $(".video-main").html(`

`); require(["ima"], function() { var player = videojs('article-video', { controls: true, // autoplay: true, // muted: true, controlBar: { pictureInPictureToggle: false }, playbackRates: [0.5, 0.75, 1, 1.25, 1.5, 2], poster: main_video['meta']['largeThumbnail'], sources: [{src: main_video['source'], type: 'application/x-mpegURL'}], tracks: [{src: main_video['subtitle'], kind:'captions', srclang: 'en', label: 'English', default: true}] },function() { player.qualityLevels(); try { player.hlsQualitySelector(); } catch (error) { console.log("HLS not working - ") } } ); const video = document.querySelector("video"); const events =[ { 'name':'play', 'callback':()=>{videoPlayCallback(main_video['slug'])} }, ]; events.forEach(event=>{ video.addEventListener(event.name,event.callback); }); }, function (err) { var player = videojs('article-video'); player.createModal('Something went wrong. Please refresh the page to load the video.'); }); /*let video_date = main_video['time']; video_date = video_date.split("/"); video_date = formatDate(video_date[2], video_date[1], video_date[0]); let share_section_content = `

${video_date}

`;*/ let hasLikeBtn = false; // console.log(share_section_content); var data = {}; if(false){ try { if((loginData && loginData.isLoggedIn == true)){ const resp = await fetch(`${API_SCRIPT_URL}logged-in-video-details/${main_video['slug']}/`,{ credentials: 'include' }) if(resp.status == 200 || resp.status == 201){ data = await resp.json(); share_section_content+= `

`; hasLikeBtn = true; } else { share_section_content+= `

`; } } else { share_section_content+= `

`; } //Load share section // $(".video-share-section").html(share_section_content); // let exitCond = 0; // const delay = (delayInms) => { // return new Promise(resolve => setTimeout(resolve, delayInms)); // } // while(!loginData){ // let delayres = await delay(1000); // exitCond+=1; // console.log(exitCond); // if(exitCond>5){ // break; // } // } // console.log(loginData); /*if(hasLikeBtn && loginData && loginData.isLoggedIn == true){ setLiked(data.liked) setSaved(data.watchlist) }*/ } catch (error) { console.log(error); } } //Load video content like title, description if(false){ $(".video-content-section").html(`

${main_video['title']}

${hideMainVideoDescription(main_video['description'], main_video['id'])}

${getTagsString(main_video['category'])} ${(course_link.length)? `

View Course

`:''} `); let related_vidoes = main_video['recommendations']; if(!!videos && videos.length>0){ //Load related videos $(".related-videos-content").html(getvideosContent()); } } //show video content element = document.getElementById('article-video-tab-content'); element.style.display = 'block'; $('.spinner-loading-overlay:eq(0)').remove(); $('.spinner-loading-overlay:eq(0)').remove(); } await showMainVideoContent(video_data, course_link); // fitRelatedVideosDescription(); } catch (error) { console.log(error); } } getVideoData(); /* $(window).resize(function(){ onWidthChangeEventsListener(); }); $('#video_nav_tab').click('on', function(){ fitRelatedVideosDescription(); });*/ });

Quick Sort Algorithm - GeeksforGeeks (2024)

References

Top Articles
Latest Posts
Article information

Author: Geoffrey Lueilwitz

Last Updated:

Views: 6207

Rating: 5 / 5 (80 voted)

Reviews: 87% of readers found this page helpful

Author information

Name: Geoffrey Lueilwitz

Birthday: 1997-03-23

Address: 74183 Thomas Course, Port Micheal, OK 55446-1529

Phone: +13408645881558

Job: Global Representative

Hobby: Sailing, Vehicle restoration, Rowing, Ghost hunting, Scrapbooking, Rugby, Board sports

Introduction: My name is Geoffrey Lueilwitz, I am a zealous, encouraging, sparkling, enchanting, graceful, faithful, nice person who loves writing and wants to share my knowledge and understanding with you.