Gnome Sort ใช้งานได้ครั้งละหนึ่ง lement และนำไปที่ตำแหน่งจริง ให้เรามาดูตัวอย่างการใช้งาน Gnome Sort −
ตัวอย่าง
import java.util.Arrays;
public class Demo{
static void gnome_sort(int my_arr[], int n){
int index = 0;
while (index < n){
if (index == 0)
index++;
if (my_arr[index] >= my_arr[index - 1])
index++;
else{
int temp = 0;
temp = my_arr[index];
my_arr[index] = my_arr[index - 1];
my_arr[index - 1] = temp;
index--;
}
}
return;
}
public static void main(String[] args){
int my_arr[] = { 34, 67, 89, 11, 0 , -21 };
gnome_sort(my_arr, my_arr.length);
System.out.println("The array after perfroming gnome sort on it is ");
System.out.println(Arrays.toString(my_arr));
}
} ผลลัพธ์
The array after perfroming gnome sort on it is [-21, 0, 11, 34, 67, 89]
คลาสชื่อ Demo มีฟังก์ชันสแตติกชื่อ 'gnome_sort' ในที่นี้ ตัวแปร 'ดัชนี' ถูกกำหนดให้เป็น 0 หากค่าดัชนีนั้นน้อยกว่าความยาวของอาร์เรย์ ค่าดัชนีจะถูกตรวจสอบเป็น 0 หากเป็น 0 ค่านั้นจะเพิ่มขึ้น 1 มิฉะนั้น หากค่าที่ ดัชนีเฉพาะมีค่ามากกว่าค่าที่ 'index-1' ของอาร์เรย์ ตัวแปรชื่อ 'temp' ถูกกำหนดเป็น 0 และองค์ประกอบจะถูกสลับ ค่า 'ดัชนี' ลดลง
ในฟังก์ชันหลัก อาร์เรย์ถูกกำหนดด้วยค่าบางอย่าง และฟังก์ชัน 'gnome_sort' จะถูกเรียกใช้ในอาร์เรย์นี้และความยาวของอาร์เรย์ เอาต์พุตถูกพิมพ์บนคอนโซล