Shell Sort

Speed

Number of Elements

[Range: 10-100]

Implementations

          
            void shellSort(int array[], int n){
              int j;

              for (int gap = n / 2; gap > 0; gap /= 2){

                for (int i = gap; i < n; i++){

                  int temp = array[i];
                  for (j = i; j >= gap && array[j - gap] > temp; j = j - gap){
                    array[j] = array[j - gap];
                  }
                  array[j] = temp;
                }
              }
            }
          
        
          
            def shellSort(array):
              n = len(array)
              gap = n//2

              while gap > 0:
                j = gap
                
                while j < n:
                  i = j - gap

                  while i >= 0:
                    if array[i + gap] > array[i]:
                      break
                    
                    else:
                      array[i + gap], array[i] = array[i], array[i + gap]

                    i = i - gap

                  j = j + 1

                gap = gap//2
          
        
          
            function shellSort(array){
              var n = array.length;
              var j;
              
              for (let gap = Math.floor(n/2); gap > 0; gap = Math.floor(gap/2)){

                for (let i = gap; i < n; i++){
                  let temp = array[i];

                  for (j = i; j >= gap && array[j - gap] > temp; j = j - gap){
                    array[j] = array[j - gap];
                  }
                  array[j] = temp;
                }
              }
            }
          
        

About Shell Sort

The Shell sorting method is a variant of the Insertion Sort. The difference between the two is that a Shell sort allows the swapping of two indecies that are further away (as opposed to neighboring indecies in an Insertion Sort).

While the Insertion Sort is a stable sort, the Shell Sort is not. The Shell Sort is also an in-place sort, meaning that it does not require any additional memory to sort the array.


Time Complexity

The Shell sorting method has a time complexity of: O(N2)