यहां हम देखेंगे कि सूक्ति सॉर्ट कैसे काम करता है। यह एक और छँटाई एल्गोरिथ्म है। इस दृष्टिकोण में यदि सूची पहले से ही क्रमबद्ध है तो इसमें ओ (एन) समय लगेगा। तो सबसे अच्छा मामला समय जटिलता ओ (एन) है। लेकिन औसत मामला और सबसे खराब स्थिति जटिलता ओ (एन ^ 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