0

my teacher said that line for (int j = i - step; j >= 0; j = j - step) spoils the whole essence of sorting. he said that I need to use the inset sorting function and insert it into the shell sorting. How can I do this?

template < typename T >
void swap(T* arr, int j, int step)
{
    T value = arr[j];
    arr[j] = arr[j + step];
    arr[j + step] = value;
}

template < typename T >
void shell_sort(T* arr, int length)
{
    for (int step = length / 2; step > 0; step = step / 2)  
    {
        for (int i = step; i < length; i++)                 
        {
            for (int j = i - step; j >= 0; j = j - step)    
            {
                if (arr[j] > arr[j + step])                 
                {
                    swap(arr, j, step);                     
                }
            }
        }
    }
}
2
  • Google "shell sort" you should find lots of explanations of the algorithm. Commented Feb 24, 2018 at 7:57
  • How about this? for (int j = i - step; j >= 0 && arr[j] > arr[j + step]; j -= step) Commented Feb 24, 2018 at 8:03

1 Answer 1

1

You can go for recursive shell sort like this:

template < typename T >
 int shell_sort(T* arr,  int length)
 {
    if (length <= 1)    return length;
    length = shell_sort(arr,length - 1);
    T value = arr[length];
    T i = length - 1;
    while ((i >= 0) && (arr[i] > value)) {
        arr[i + 1] = arr[i];
        i--;
    }
    arr[i + 1] = value;
    return length + 1;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.