C++ 排序程序?
梳状排序和冒泡排序的基本思想是相同的。换句话说,梳状排序是对冒泡排序的改进。在冒泡排序技术中,在每个阶段,将项目与下一个项目进行比较。但对于梳状排序,项目按特定间隙进行排序。完成每个阶段后,间隙会减少。这种排序的减小因数或收缩因数为 1.3。这意味着完成每个阶段后,间隙将除以 1.3。最佳情况下的时间复杂度为 O(n log n)。平均情况为 O(n2/2nP)(p 是增量数量),最坏情况为 O(n2)。
算法
CombSort(阵列,大小)
输入 − 数据数组和数组中的总数
输出 − 已排序的数组
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
广告