用于Gnome排序的C ++程序?
在这里,我们将看到gnome排序的工作原理。这是另一种排序算法。在这种方法中,如果列表已经排序,则将花费O(n)时间。因此,最佳情况下时间复杂度为O(n)。但是平均情况和最坏情况下的复杂度为O(n^2)。现在让我们来看一下有关这种排序技术的算法。
算法
gnomeSort(arr,n)
begin
index := 0
while index < n, do
if index is 0, then
index := index + 1
end if
if arr[index] >= arr[index -1], then
index := index + 1
else
exchange arr[index] and arr[index - 1]
index := index - 1
end if
done
end示例
#include<iostream>
using namespace std;
void gnomeSort(int arr[], int n){
int index = 0;
while(index < n){
if(index == 0) index++;
if(arr[index] >= arr[index - 1]){ //if the element is greater than previous one
index++;
} else {
swap(arr[index], arr[index - 1]);
index--;
}
}
}
main() {
int data[] = {54, 74, 98, 154, 98, 32, 20, 13, 35, 40};
int n = sizeof(data)/sizeof(data[0]);
cout << "Sorted Sequence ";
gnomeSort(data, n);
for(int i = 0; i <n;i++){
cout << data[i] << " ";
}
}输出结果
Sorted Sequence 13 20 32 35 40 54 74 98 98 154
热门推荐
10 新年门口花束祝福语简短
11 盘锦结婚祝福语大全简短
12 父母生日祝福语 简短独特
13 家庭恩爱祝福语简短英文
14 高考俄语祝福语大全简短
15 虎年祝福语 诗句唯美简短
16 生日婚礼祝福语简短精辟
17 虎年喝酒拜年祝福语简短
18 教师闺蜜祝福语简短