梳状排序
梳状排序和冒泡排序的基本思想是相同的。换句话说,梳状排序是对冒泡排序的改进。在冒泡排序技术中,每一阶段都会将一个元素与下一个元素进行比较。但在梳状排序中,元素会按特定的间隔进行排序。每个阶段完成后,间隔就会减小。这种排序的递减因子或收缩因子是 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
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP