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›Shell Sort
    Data Structures & AlgorithmsTopic 14 of 37

    Shell Sort

    4 minread
    636words
    Beginnerlevel

    Shell Sort

    Description: Shell sort is an optimization of insertion sort that allows the exchange of items that are far apart. It uses a gap sequence to determine which elements to compare and swap. The idea is to allow the elements to move more quickly to their correct positions, effectively reducing the overall sorting time.

    How It Works

    1. Choose Gaps: Start with a large gap and reduce it over time. The first gap might be half the size of the array, then a quarter, and so on.
    2. Sort Subarrays: For each gap, perform a gapped insertion sort. This means that you take elements that are a specific distance apart and sort them as if they are in a smaller array.
    3. Repeat: Continue this process until the gap is reduced to 1. A final insertion sort will finish the sorting.

    Time Complexity

    • Worst Case: O(n3/2)O(n^{3/2})O(n3/2) — depends on the gap sequence used.
    • Average Case: O(nlog⁡n)O(n \log n)O(nlogn) — with an optimal gap sequence.
    • Best Case: O(n)O(n)O(n) — occurs when the array is already sorted.

    Space Complexity

    • Space Complexity: O(1)O(1)O(1) — Shell sort is an in-place sorting algorithm, requiring a constant amount of additional space.

    Stability

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

    Example Code

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

    #include <iostream>
    using namespace std;
    
    void shellSort(int arr[], int n) {
        // Start with a big gap, then reduce the gap
        for (int gap = n / 2; gap > 0; gap /= 2) {
            // Do a gapped insertion sort for this gap size
            for (int i = gap; i < n; i++) {
                int temp = arr[i]; // Element to be positioned
                int j; 
    
                // Shift earlier gap-sorted elements up until the correct location for arr[i] is found
                for (j = i; j >= gap && arr[j - gap] > temp; j -= gap) {
                    arr[j] = arr[j - gap];
                }
                arr[j] = temp; // Put temp (the original arr[i]) in its correct location
            }
        }
    }
    
    int main() {
        int arr[] = {12, 34, 54, 2, 3};
        int n = sizeof(arr) / sizeof(arr[0]);
        shellSort(arr, n);
    
        cout << "Sorted array: ";
        for (int i = 0; i < n; i++) {
            cout << arr[i] << " ";
        }
        cout << endl;
    
        return 0;
    }
    

    Explanation of the Code

    1. Function Definition: The shellSort function takes an array and its size as parameters.
    2. Gap Selection: The outer loop starts with a gap of half the size of the array and continues halving the gap until it becomes zero.
    3. Gapped Insertion Sort:
      • The inner loop performs a gapped insertion sort by comparing elements that are gap distance apart.
      • Elements are shifted up to make space for the current element (temp) to be placed in its correct position.
    4. Output: After sorting, the program prints the sorted array.

    Conclusion

    Shell sort improves upon insertion sort by allowing the exchange of distant elements, thus reducing the number of comparisons and movements needed as the gaps decrease. While not as efficient as more advanced algorithms like quick sort or merge sort for large datasets, it is simple to implement and can be very effective for smaller lists. Its in-place nature and lower overhead make it a useful choice for certain applications where memory usage is a concern.

    Previous topic 13
    Heap Sort
    Next topic 15
    Radix 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 count636
      Code examples0
      DifficultyBeginner