ที่นี่เราจะดูว่าการเรียงลำดับของ 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