用于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 妈妈生日祝福语简短励志