用于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 好听的元旦简短祝福语