梳排序
梳排序和冒泡排序的基本思想相同。换句话说,梳排序对冒泡排序进行了改进。在冒泡排序技术中,每个阶段将各项目与下一项目进行比较。但是对于梳排序,按照特定间隔对项目进行排序。每个阶段完成后,间隔都会减小。此排序的递减因子或收缩因子是 1.3。这意味着在完成每个阶段后,间隔将除以 1.3。
梳排序技术的复杂性
- 时间复杂度:最佳情况下的 O(n log n)。平均情况下对于 O(n^2/2^p)(p 是增量数),最差情况下是 O(n^2)。
- 空间复杂度:O(1)
输入和输出
Input: A list of unsorted data: 108 96 23 74 12 56 85 42 13 47 Output: Array before Sorting: 108 96 23 74 12 56 85 42 13 47 Array after Sorting: 12 13 23 42 47 56 74 85 96 108
算法
CombSort(array, size)
输入 −数据数组,以及数组中的总数
输出 −已排序的数组
Begin gap := size flag := true while the gap ≠ 1 OR flag = true do gap = floor(gap/1.3) //the the floor value after division if gap < 1 then gap := 1 flag = false for i := 0 to size – gap -1 do if array[i] > array[i+gap] then swap array[i] with array[i+gap] flag = true; done done End
示例
#include<iostream> #include<algorithm> using namespace std; void display(int *array, int size) { for(int i = 0; i<size; i++) cout << array[i] << " "; cout << endl; } void combSort(int *array, int size) { int gap = size; //initialize gap size with size of array bool flag = true; while(gap != 1 || flag == true) { gap = (gap*10)/13; //minimize gap by shrink factor if(gap<1) gap = 1; flag = false; for(int i = 0; i<size-gap; i++) { //compare elements with gap if(array[i] > array[i+gap]) { swap(array[i], array[i+gap]); flag = true; } } } } 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); combSort(arr, n); cout << "Array after Sorting: "; display(arr, n); }
输出
Enter the number of elements: 10 Enter elements: 108 96 23 74 12 56 85 42 13 47 Array before Sorting: 108 96 23 74 12 56 85 42 13 47 Array after Sorting: 12 13 23 42 47 56 74 85 96 108
广告