Javatpoint Logo
Javatpoint Logo

Quick Sort Algorithm in C++

An Introduction to the Quick Sort Algorithm

In computer science and data processing, sorting is a fundamental procedure. It entails putting a group of objects or components in a certain order, usually according to some criterion and in either ascending order or descending order. Applications like databases, search engines, and information retrieval all depend on sorting.

The Quick Sort Algorithm

An effective and popular comparison-based sorting algorithm is Quick Sort, sometimes referred to as partition-exchange sort. Tony Hoare created it in 1960, and it has since evolved into a common technique for sorting. The speed of Quick Sort is well recognized, especially for big datasets, and it is frequently used as a standard for other sorting algorithms.

Quick Sort's main concept is to break a dataset into smaller subproblems, independently sort each subproblem, and then merge the sorted subproblems to get the final sorted dataset. A divide-and-conquer tactic is used to complete this procedure. The dataset splitting process used in Quick Sort is its main activity.

The Partition Step

The Partition Step is a heart of quick Sort Algorithm. It works as follows:

  1. From the dataset, pick a pivot element. Different methods may be used to choose the pivot element, and the choice of the pivot can influence how well the algorithm performs.
  2. Rearrange the elements in the dataset so that everything on the left is bigger than the pivot and everything on the right is less than the pivot. Now, the pivot element is at the last position of the sort.
  3. Recursively apply the partitioning step to the subarrays of the left and right of the pivot until the data is sorted.

Choosing the Pivot

The pivot element and partition techniques that are used have a significant impact on Quick Sort's efficiency. There are several methods for choosing the pivot, such as:

Choosing the First Element as a pivot: The first element of the dataset is always selected as the pivot in this simple method.

Choosing the Last Element as a pivot: Similar to the prior approach, but with the final piece chosen as the pivot.

Selecting the Median-of-Three: The pivot is chosen using this technique as the median of the dataset's first, middle, and last components. It seeks to lessen the likelihood of running into worst-case scenarios.

Random pivot Selection: In this method, the pivot is selected randomly from the dataset. The danger of worst-case events may be reduced as a result.

Algorithm steps of the Quick Sort

1. Choose a pivot Element:

  • Choose a pivotal component from the list. The algorithm's effectiveness may be impacted by the pivot option. The first element, the final element, the midway element, or a random element are examples of common pivot selection procedures.

2. Partition the Array:

  • Rearrange the elements of the array so that all those that are less than the pivot are moved to the left of it, and those that are larger than that are moved to the right.
  • The pivot element now has been sorted to its last position.

3. Recursively Sort Subarray:

  • The subarray to the left of the pivot, which has less elements than the pivot, is subjected to the Quick Sort algorithm in recursive fashion.
  • The subarray to the right of the pivot, which contains entries larger than the pivot, is subjected to the Quick Sort algorithm iteratively.

4. Combine sorted Subarrays:

The array as a whole is sorted once all recursive calls are finished since each pivot element is at the proper end position.

5. Repeat until the entire array is sorted:

When the entire array is sorted, continue the steps of choosing a pivot, splitting the array, and recursively sorting subarrays once again.

Here is the pseudocode representation of the Quick Sort Algorithm:

The partitioning procedure and the recursive sorting of subarrays are two of the primary phases of the Quick Sort algorithm that are described in this pseudo-code. The method repeats itself until the entire array is sorted, each pivot element being in the proper place.

Quick Sort Implementation in C++

Let's look at the C++ implementation of the Quick Sort algorithm now that we are familiar with its fundamentals. Implementing the partitioning phase first, then the recursive sorting procedure, is what we'll do first.

Explanation

In C++ implementation, we have defined three functions:

  • 'Partition': This function accepts a vector 'arr' along with two integer arguments, 'low' and 'high', that define the range of entries to be partitioned. It selects the first element as the pivot and flips the order of the vector's elements so that everything to the left of the pivot is greater than everything to the right. The pivot element's index is what is returned.
  • 'quickSort:' The Quick Sort method is mostly implemented by this sorting function. The range of elements to be sorted is specified by the vector 'arr' and the indices 'low and high'. Up until the full array is sorted, it recursively splits the array and sorts the left and right subarrays.
  • 'printArray': This function is used to print the elements of the array.
  • In the 'main' function, we show how to sort an example vector of numbers using the 'quickSort' function. The Quick Sort method is used to sort the array, which is then printed after printing the original array.

Output

Original Array: 12 4 5 6 7 3 1 15 
Sorted Array: 1 3 4 5 6 7 12 15

Performance Analysis

In both ordinary and ideal circumstances, Quick Sort is renowned for its outstanding performance. However, when the pivot decision regularly results in imbalanced partitions, its worst-case time complexity is O(n2). The median-of-three or random pivot selection procedures are frequently employed to reduce this risk.

Where 'n' is the number of elements to be sorted, Quick Sort has an average and best-case time complexity of O(n*log(n)). In particular, for huge datasets, this makes it one of the quickest sorting methods. Additionally, as Quick Sort is an in-place sorting algorithm, there is no need for additional RAM to store the sorted data.

The space needed for the recursive function calls and the call stack is represented by the Quick Sort space complexity, which is O(log(n)). Generally speaking, this space complexity is quite effective, which qualifies Quick Sort for sorting huge datasets.

Some Practical Use Cases

  1. Sorting Large Databases: In database management systems, Quick Sort is frequently used to efficiently sort huge amounts of data.
  2. Search Algorithms: When data has to be sorted before searching, it is employed in search methods like binary search.
  3. Numerical analysis: For sorting numerical data, Quick Sort is utilized in scientific computing and numerical analysis.
  4. File Systems: A quick Sort is a good option since file systems frequently need to swiftly organize and retrieve data.

Advantages and Disadvantages of the Quick Sort Algorithm in C++

The effective and quick sorting algorithm known as Quick Sort is widely used. It is a popular option for sorting in a variety of applications because of its many benefits. Like every algorithm, it does, however, have some drawbacks and restrictions. We will examine the advantages and disadvantages of Quick Sort in C++ in this post to help you understand when and why to use it.

Advantages of Quick Sort

  1. High Efficiency: Large datasets are especially well-suited for Quick Sort's outstanding efficiency. Its typical time complexity is O(n*log(n)), making it quicker than many other sorting algorithms like Bubble Sort and Insertion Sort. In circumstances when performance is important, this efficiency is a considerable benefit.
  2. In-Place Sorting: As an in-place sorting method, Quick Sort sorts the data without the need for additional memory or storage. In contexts with limited memory, it might be crucial to sort the components inside the supplied array itself.
  3. Cache Friendly: The algorithmic design of Quick Sort often results in high cache performance. It has strong locality of reference, which reduces cache misses while accessing data pieces and speeds up the process.
  4. Versatility in Pivot Selection: Quick Sort's configurable pivot element selection enables programmers to customize the algorithm to meet their own requirements. Worst-case scenarios are less likely when pivot selection algorithms are modified to optimize performance for various input data types.

Last and First Pivot Selection: Initial and Final Pivot These tactics are straightforward and simple to use. They decide to use the first or final element, respectively, as the pivot.

Median of Three Pivots: The pivot is chosen using this technique as the median of the dataset's first, middle, and last components. The worst-case danger is lessened as a result.

Random Pivot Selection: The method becomes less predictable and more resistant to hostile input data by using a random element as the pivot.

  1. Parallelization Potential: Quick Sort may effectively be parallelized, making it possible for it to benefit from distributed computing settings and multi-core computers. This allows for the concurrent sorting of very big datasets, greatly enhancing its performance.
  2. Widely Used: An established and popular sorting algorithm is Quick Sort. Due to its effectiveness and speed, it is frequently used as the default sorting technique in computer languages and libraries. Developers are, therefore, frequently acquainted with its implementation and behavior.

Disadvantages of Quick Sort

  1. Worst-case Time Complexity: The worst-case temporal complexity of Quick Sort is one of its main drawbacks. In the worst situation, Quick Sort can decline to O(n²), where 'n' is the number of items to be sorted, when the pivot selection constantly leads to imbalanced partitions (for example, by always choosing the smallest or biggest element as the pivot). In some circumstances, this worst-case scenario may out to be a serious disadvantage.
  2. Sensitivity to Pivot Selection: The pivot element that is selected will have a significant impact on Quick Sort's performance. Although there are ways for pivot selection to lessen this sensitivity, a poor pivot selection might result in subpar performance or even the worst-case circumstances.
  3. Lack of Stability: The sorting algorithm Quick Sort is not reliable. When two elements have identical keys, stability in sorting means that their relative order in the sorted output stays the same as in the initial input. Stability is not a given with Quick Sort, even if it could be crucial in some applications.
  4. Recursive Nature: While this may be overcome by utilizing tail recursion or an iterative technique, it adds complexity to the solution and can cause stack overflow issues when sorting very big datasets.
  5. Not Adaptive: Since Quick Sort is not an adaptive sorting algorithm, sorting partially sorted data does not greatly enhance its performance. When given partially sorted input, some sorting algorithms, like Insertion Sort, perform better.
  6. Not Suitable for Linked list: The most effective method for sorting linked lists is not Quick Sort. It doesn't fully use the linked list data structure since it relies on random access to items, which might lead to subpar performance when compared to alternative sorting algorithms like Merge Sort or Insertion Sort.

The Conclusion

In computer science and several applications, Quick Sort is a flexible and incredibly effective sorting algorithm. For sorting huge datasets, it is a popular option because of its speed, in-place nature, and versatility. Even though it can have a worst-case temporal complexity of O(n²), in reality, this problem can be mitigated by using appropriate pivot selection techniques. Quick Sort performs better than many other sorting algorithms when used properly and is crucial to the fields of computer science and data processing.







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA