ScholarQuill logoScholarQuillUniversity Notes
My Semester
Explore Notes
Past Papers12 New
Video CoursesNew
Search
Settings
Study Tools
GPA/CGPA Calculator
Schedule & To-Do
Student Portal
Contact
Contact
ScholarQuill logo
My Semester
Explore Notes
Past Papers12 New
Video CoursesNew
Search
Settings
GPA/CGPA Calculator
Schedule & To-Do
Student Portal
Contact
ScholarQuill logoScholarQuillUniversity Notes
Study PortalCC-213Quick Sort
Ctrl + K
Login
Explore
Search
Semester
Papers
CGPA
    CC-213

    Data Structures & Algorithms

    Progress0 / 37 done
    Topics37
    1Abstract Data Types2Complexity Analysis3Big Oh Notation4Stacks (Linked Lists and Array Implementations)5Recursion and analyzing recursive algorithms6Divide and Conquer Algorithms7Sorting Algorithms8Selection Sort9Insertion Sort10Merge Sort11Quick Sort12Bubble Sort13Heap Sort14Shell Sort15Radix Sort16Bucket Sort17Queue18Dequeuer19Priority Queues (linked and array implementations of queues)20Linked List and Its Various Types21Sorted Linked List22Searching an Unsorted Array23Binary Search for Sorted Arrays24Hashing and Indexing25Open Addressing and Chaining26Trees and Tree Traversals27Binary Search Trees28Heaps29M-Way Trees30Balanced Trees31Graphs32Breadth-First Traversal33Depth-First Traversal34Topological Order35Shortest Path36Adjacency Matrix and Adjacency List Implementations37Memory Management and Garbage Collection
    4 min read
    Topic 11 of 37
    Topic Study Note Illustration
    11

    Quick Sort

    Visual Reference Sorting Algorithm Wikipedia Description : Quick sort is a highly efficient sorting algorithm that follows the divide-and-conquer principle. It works by selecting a "pivot" element...

    Quick Sort

    Sorting algorithm
    Visual ReferenceSorting Algorithm
    Wikipedia

    Description: Quick sort is a highly efficient sorting algorithm that follows the divide-and-conquer principle. It works by selecting a "pivot" element from the array and partitioning the other elements into two subarrays: those less than the pivot and those greater than the pivot. The subarrays are then sorted recursively.

    How It Works

    1. Choose a Pivot: Select an element from the array as the pivot (commonly the last element).
    2. Partitioning: Rearrange the array so that elements less than the pivot come before it and elements greater than the pivot come after it. After partitioning, the pivot is in its final position.
    3. Recursion: Recursively apply the above steps to the subarrays on the left and right of the pivot.

    Time Complexity

    • Worst Case: O(n2)O(n^2)O(n2) — occurs when the smallest or largest element is consistently chosen as the pivot (e.g., for an already sorted array).
    • Average Case: O(nlog⁡n)O(n \log n)O(nlogn) — typical case when the pivot is chosen randomly or is the median.
    • Best Case: O(nlog⁡n)O(n \log n)O(nlogn) — when the pivot divides the array into nearly equal halves.

    Space Complexity

    • Space Complexity: O(log⁡n)O(\log n)O(logn) — due to the recursive stack space; however, it can go up to O(n)O(n)O(n) in the worst case if not implemented with tail recursion.

    Stability

    • Stability: Quick sort is not a stable sort. Equal elements may not maintain their relative order after sorting.

    Example Code

    Here's a C++ implementation of quick sort:

    #include <iostream>
    using namespace std;
    
    int partition(int arr[], int low, int high) {
        int pivot = arr[high]; // Choosing the last element as the pivot
        int i = low - 1; // Index of smaller element
    
        for (int j = low; j < high; j++) {
            // If current element is smaller than or equal to pivot
            if (arr[j] <= pivot) {
                i++; // Increment index of smaller element
                swap(arr[i], arr[j]); // Swap elements
            }
        }
        swap(arr[i + 1], arr[high]); // Place pivot in the correct position
        return i + 1; // Return the partitioning index
    }
    
    void quickSort(int arr[], int low, int high) {
        if (low < high) {
            int pi = partition(arr, low, high); // Partitioning index
    
            // Recursively sort elements before and after partition
            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]);
        quickSort(arr, 0, n - 1);
    
        cout << "Sorted array: ";
        for (int i = 0; i < n; i++) {
            cout << arr[i] << " ";
        }
        cout << endl;
    
        return 0;
    }
    

    Explanation of the Code

    1. Function Definitions:

      • partition: Partitions the array around the pivot, placing elements less than the pivot to its left and those greater to its right.
      • quickSort: Recursively sorts the array using the partitioning method.
    2. Choosing the Pivot: The last element of the array is chosen as the pivot.

    3. Partitioning Process:

      • The partition function iterates through the array, comparing each element with the pivot.
      • Elements smaller than or equal to the pivot are swapped to the front.
      • Finally, the pivot is placed in its correct position, and the function returns its index.
    4. Recursive Sort: The quickSort function recursively sorts the subarrays defined by the pivot's position.

    5. Output: The sorted array is printed after the sorting is complete.

    Conclusion

    Quick sort is a powerful and widely used sorting algorithm due to its average-case efficiency and the ability to sort in-place. Its O(nlog⁡n)O(n \log n)O(nlogn) average time complexity makes it faster than many other algorithms for larger datasets. However, care must be taken in choosing the pivot to avoid worst-case scenarios, especially for already sorted arrays. Despite its lack of stability, quick sort remains a popular choice for sorting in various applications.

    ← Previous topic 10
    Merge Sort
    Next topic 12 →
    Bubble Sort

    Past Papers

    Open this section to view and download past papers

    Click on Show Past Papers to load available exam papers.

    Reading Progress
    0%
    4mremaining
    747words
    Beginnerlevel
    On This Page

    No headings found

    Study Toolkit

    Subject Portal

    Data Structures & Algorithms