C++ 编程实现希尔排序
希尔排序技术是基于插入排序的。在插入排序中,有时我们需要移动较大的块,才能将项插入正确位置。使用希尔排序,我们可以避免大量移动。排序使用特定的间隔来进行。每次通过后,间隔变小,形成较小的间隔。
希尔排序技术的复杂度
时间复杂度:最佳情况为 O(n log n),对于其他情况,这取决于间隙序列。
空间复杂度:O(1)
Input − The unsorted list: 23 56 97 21 35 689 854 12 47 66 Output − Array after Sorting: 12 21 23 35 47 56 66 97 689 854
算法
shellSort(array, size)
输入:一个数据数组,以及数组中的总数
输出:已排序的数组
Begin for gap := size / 2, when gap > 0 and gap is updated with gap / 2 do for j:= gap to size– 1 do for k := j-gap to 0, decrease by gap value do if array[k+gap] >= array[k] break else swap array[k + gap] with array[k] done done done End
示例代码
#include<iostream> using namespace std; void swapping(int &a, int &b) { //swap the content of a and b int temp; temp = a; a = b; b = temp; } void display(int *array, int size) { for(int i = 0; i<size; i++) cout << array[i] << " "; cout << endl; } void shellSort(int *arr, int n) { int gap, j, k; for(gap = n/2; gap > 0; gap = gap / 2) { //initially gap = n/2, decreasing by gap /2 for(j = gap; j<n; j++) { for(k = j-gap; k>=0; k -= gap) { if(arr[k+gap] >= arr[k]) break; else swapping(arr[k+gap], arr[k]); } } } } int main() { int n; cout << "Enter the number of elements: "; cin >> n; int arr[n]; //create an array with given number of elements cout << "Enter elements:" << endl; for(int i = 0; i<n; i++) { cin >> arr[i]; } cout << "Array before Sorting: "; display(arr, n); shellSort(arr, n); cout << "Array after Sorting: "; display(arr, n); }
输出
Enter the number of elements: 10 Enter elements: 23 56 97 21 35 689 854 12 47 66 Array before Sorting: 23 56 97 21 35 689 854 12 47 66 Array after Sorting: 12 21 23 35 47 56 66 97 689 854
广告