用于进行 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP