Shell | C ++ implementation of Shell - Metzner Sort ; Function to swap two elements ; Function to sort arr [ ] using Shell Metzner sort ; Declare variables ; Set initial step size to the size of the array ; Step size decreases by half each time ; k is the upper limit for j ; j is the starting point ; i equals to smaller value ; l equals to larger value ; Compare and swap arr [ i ] with arr [ l ] ; Decrease smaller value by step size ; Increment the lower limit of i ; Function to print the contents of an array ; Driver code ; Sort the array using Shell Metzner Sort ; Print the sorted array
#include <bits/stdc++.h> NEW_LINE using namespace std ; void swap ( int & a , int & b ) { int temp = a ; a = b ; b = temp ; } void sort_shell_metzner ( int arr [ ] , int n ) { int i , j , k , l , m , temp ; m = n ; while ( m > 0 ) { m /= 2 ; k = n - m ; j = 0 ; do { i = j ; do { l = i + m ; if ( arr [ i ] > arr [ l ] ) { swap ( arr [ i ] , arr [ l ] ) ; i -= m ; } else break ; } while ( i >= 0 ) ; j ++ ; } while ( j <= k ) ; } } void printArray ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) cout << arr [ i ] << " ▁ " ; } int main ( ) { int arr [ ] = { 0 , -2 , 8 , 5 , 1 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; sort_shell_metzner ( arr , n ) ; printArray ( arr , n ) ; return 0 ; }