用于进行 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

更新于: 2019 年 7 月 30 日

372 次浏览

开启您的 职业生涯

完成课程获得认证

开始
广告
© . All rights reserved.