学习目标:
Shell Sort
学习时间:
2021/7/28 20:00 ~ 21:30
学习内容:
1.what
the algorithm breaks an original set into smaller subsets and then each of those is sorted using Insertion sort.
2.how
- how it makes the subsets is not straightforward.
- It doesn’t choose neighboring elements to form a subset as we might expect.
- Rather, shell sort uses the so-called interval or gap for subset creation.
3.example
if we have the gap I, it means that one subset will contain the elements that are I positions apart.
4.process
- Firstly, the algorithm sorts the elements that are far away from each other.
- Then, the gap becomes smaller and closer elements are compared.
- This way, some elements that aren’t in a correct position can be positioned faster than
- if we made the subsets out of the neighboring elements.
学习产出:
- We first created a gap sequence with a for loop
- then did the insertion sort for each gap size
public void sort(int arrayToSort[]) {
int n = arrayToSort.length;
for (int gap = n / 2; gap > 0; gap /= 2) {
for (int i = gap; i < n; i++) {
int key = arrayToSort[i];
int j = i;
while (j >= gap && arrayToSort[j - gap] > key) {
arrayToSort[j] = arrayToSort[j - gap];
j -= gap;
}
arrayToSort[j] = key;
}
}
}