用于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 祝福语驱散霉运的话简短