ScholarQuill logoScholarQuillUniversity Notes
  • Notes
  • Past Papers
  • Blogs
  • Todo
Login
ScholarQuill logoScholarQuillUniversity Notes
Login
NotesPast PapersBlogsTodo
More
SubjectsDiscussionCGPA CalculatorGPA CalculatorStudent PortalCourse Outline
About
About usPrivacy PolicyReportContact
Notes
Past Papers
Blogs
Todo
Analytics
    Current Subject
    🧩
    Data Structures & Algorithms
    CC-213
    Progress0 / 37 topics
    Topics
    1. Abstract Data Types2. Complexity Analysis3. Big Oh Notation4. Stacks (Linked Lists and Array Implementations)5. Recursion and analyzing recursive algorithms6. Divide and Conquer Algorithms7. Sorting Algorithms8. Selection Sort9. Insertion Sort10. Merge Sort11. Quick Sort12. Bubble Sort13. Heap Sort14. Shell Sort15. Radix Sort16. Bucket Sort17. Queue18. Dequeuer19. Priority Queues (linked and array implementations of queues)20. Linked List and Its Various Types21. Sorted Linked List22. Searching an Unsorted Array23. Binary Search for Sorted Arrays24. Hashing and Indexing25. Open Addressing and Chaining26. Trees and Tree Traversals27. Binary Search Trees28. Heaps29. M-Way Trees30. Balanced Trees31. Graphs32. Breadth-First Traversal33. Depth-First Traversal34. Topological Order35. Shortest Path36. Adjacency Matrix and Adjacency List Implementations37. Memory Management and Garbage Collection
    CC-213›Quick Sort
    Data Structures & AlgorithmsTopic 11 of 37

    Quick Sort

    4 minread
    742words
    Beginnerlevel

    Quick Sort

    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 load past papers

    Click on Show Past Papers to see past papers.
    On This Page
      Reading Stats
      Est. reading time4 min
      Word count742
      Code examples0
      DifficultyBeginner