Created
June 3, 2021 22:58
-
-
Save msmoiz/054ef2a0e52a3b91acdc00c0931da23c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
template<typename T> | |
void exchange(vector<T>& list, int i, int j) | |
{ | |
T temp = list[i]; | |
list[i] = list[j]; | |
list[j] = temp; | |
} | |
/** | |
* Part of the drawback of the insertion sort | |
* is that it performs poorly when elements need to travel | |
* far, because the travel must occur one step at a time. | |
* In the worst case, the smallest item will need to be | |
* moved from the end of the list to the beginning. | |
* The shellsort aims to remedy this by creating larger | |
* jumps for each item. It proceeds by establishing a | |
* shell size, and following standard insertion sort protocol | |
* for switching bigger items with smaller items. | |
* By the time the shell size is 1, the list should be mostly | |
* in order, reducing the time complexity substantially, | |
* though its precise performance is difficult to quantify. | |
*/ | |
template<typename T> | |
void shell_sort(vector<T>& list) | |
{ | |
int shell = 0; | |
while (shell < list.size()) | |
{ | |
shell = (shell * 3) + 1; | |
} | |
while (shell > 0) | |
{ | |
for (int i = shell; i < list.size(); ++i) | |
{ | |
for (int j = i; j > 0 && list[j] < list[j - shell]; j -= shell) | |
{ | |
exchange(list, j, j - shell); | |
} | |
} | |
shell /= 3; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment