Gnome Sort
Gnome Sort :
Author(s) : Hamid Sarbazi-Azad Date : 2000Gnome sort, also called the Stefano algorithm, is a relatively simple sorting technique with a unique approach. It maintains a single 'pivot' element and compares it with the element ahead. If they are in order, the pivot is shifted one position ahead. If not, they are swapped, and the process repeats with the swapped element becoming the new pivot. This process continues until the pivot reaches the end of the array, indicating the entire array is sorted. Gnome sort has an average-case time complexity of O(n) but can degrade to O(n²) in the worst case. While potentially faster than bubble sort for some datasets, its niche nature limits its widespread adoption.
Time Complexity | O(n²) |
Best Case | O(n) |
Worst Case | O(n²) |
Space Complexity | O(1) |
Stable | Yes |
Code Integration:
* the code might contain some bugs or may not work correctly
def gnomesort(arr):
n = len(arr)
i = 0
while i < n - 1:
# If current element is smaller than the previous one, swap them
if i == 0 or arr[i] >= arr[i - 1]:
i += 1
else:
arr[i], arr[i - 1] = arr[i - 1], arr[i]
i -= 1 # Move back one position to check again
# Test array
arr = [64, 34, 25, 12, 22, 11, 90]
gnomesort(arr)
print('Sorted array is:', arr)
function gnomesort(arr) {
let n = arr.length;
let i = 0;
while (i < n - 1) {
// If current element is smaller than the previous one, swap them
if (i === 0 || arr[i] >= arr[i - 1]) {
i++;
} else {
[arr[i], arr[i - 1]] = [arr[i - 1], arr[i]]; // Swap using destructuring
i--;
}
}
// Test array
let arr = [64, 34, 25, 12, 22, 11, 90];
g nomesort(arr);
console.log('Sorted array is:', arr);
}
public static void gnomesort(int[] arr) {
int n = arr.length;
int i = 0;
while (i < n - 1) {
// If current element is smaller than the previous one, swap them
if (i == 0 || arr[i] >= arr[i - 1]) {
i++;
} else {
int temp = arr[i]; // Use a temporary variable
arr[i] = arr[i - 1];
arr[i - 1] = temp;
i--;
}
}
// Test array
int[] arr = {64, 34, 25, 12, 22, 11, 90};
g nomesort(arr);
System.out.println("Sorted array is:" + java.util.Arrays.toString(arr));
}
func gnomesort(arr []int) {
n := len(arr)
i := 0
for i < n - 1 {
// If current element is smaller than the previous one, swap them
if i == 0 || arr[i] >= arr[i-1] {
i++
} else {
arr[i], arr[i-1] = arr[i-1], arr[i]
i--
}
}
// Test array
arr := []int{64, 34, 25, 12, 22, 11, 90}
g nomesort(arr)
fmt.Println("Sorted array is:", arr)
}
void gnomesort(int arr[], int n) {
int i = 0;
while (i < n - 1) {
// If current element is smaller than the previous one, swap them
if (i == 0 || arr[i] >= arr[i - 1]) {
i++;
} else {
int temp = arr[i]; // Temporary variable for swap
arr[i] = arr[i - 1];
arr[i - 1] = temp;
i--;
}
}
// Test array
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr) / sizeof(arr[0]);
g nomesort(arr, n);
printf("Sorted array is: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
}