在shellSort中,我们对数组进行h排序以获得较大的h值。我们一直将h的值减小到1。如果每个第h个元素的所有子列表都被排序,则称数组为h排序。
// C++ implementation of Shell Sort
#include
/* function to sort arr using shellSort */
void shellSort(int arr[], int n)
{
// Start with a big gap, then reduce the gap
for (int gap = n / 2; gap > 0; gap /= 2) {
// Do a gapped insertion sort for this gap size.
// The first gap elements arr[0..gap-1] are already in gapped order
// keep adding one more element until the entire array is
// gap sorted
for (int i = gap; i < n; i += 1) {
// add arr[i] to the elements that have been gap sorted
// save arr[i] in temp and make a hole at position i
int temp = arr[i];
// shift earlier gap-sorted elements up until the correct
// location for arr[i] is found
int j;
for (j = i; j >= gap && arr[j - gap] > temp; j -= gap)
arr[j] = arr[j - gap];
// put temp (the original arr[i]) in its correct location
arr[j] = temp;
}
}
}
void printArray(int arr[], int n)
{
for (int i = 0; i < n; i++)
std::cout << arr[i] << " ";
std::cout << "\n";
}
int main()
{
int arr[] = { 12, 34, 54, 2, 3 };
int n = sizeof(arr) / sizeof(arr[0]);
std::cout << "Array before sorting: \n";
printArray(arr, n);
shellSort(arr, n);
std::cout << "Array after sorting: \n";
printArray(arr, n);
}
输出:
Array before sorting:
12 34 54 2 3
Array after sorting:
2 3 12 34 54
请参阅ShellSort上的完整文章以获取更多详细信息!
想要从精选的最佳视频中学习并解决问题,请查看有关从基础到高级C++的C++基础课程以及有关语言和STL的C++ STL课程。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程” 。