ในบทความนี้ เราจะเรียนรู้วิธีการค้นหาแบบ Linear Search แบบ Recursive (เวียนเกิด) ในอาร์เรย์ Linear Search เป็นอัลกอริทึมค้นหาที่ง่ายที่สุด ซึ่งค้นหาแบบลำดับ (sequential) ทีละรายการ
ตัวอย่างการทำงาน
สมมติข้อมูลนำเข้า (Input) คือ:
Input array: 14 20 35 47 50 65 72 81 90 99 Key element: 72
ผลลัพธ์ที่ต้องการ (Output) คือ:
The element 72 is present at position: 6
อัลกอริทึม
ขั้นตอนที่ 1 - เริ่มต้น ขั้นตอนที่ 2 - ประกาศอาร์เรย์สตริง input_array ตัวแปรจำนวนเต็ม key_element และ index ขั้นตอนที่ 3 - กำหนดค่าให้กับตัวแปรต่างๆ ขั้นตอนที่ 4 - วนลูปผ่านอาร์เรย์ กำหนดค่าที่ต้องการค้นหา เรียกใช้เมธอด recursive ขั้นตอนที่ 5 - กำหนดเงื่อนไข if: ถ้าค้นหาไม่เจอ return -1 มิฉะนั้น return ตำแหน่งขององค์ประกอบ ขั้นตอนที่ 6 - แสดงผลบนคอนโซล ขั้นตอนที่ 7 - จบการทำงาน
ตัวอย่างที่ 1: Linear Search บนจำนวนเต็ม
public class LinearSearch {
static int recSearch(int input_array[], int l, int r, int key_element) {
if (r < l)
return -1;
if (input_array[l] == key_element)
return l;
if (input_array[r] == key_element)
return r;
return recSearch(input_array, l+1, r-1, key_element);
}
public static void main(String[] args) {
int input_array[] = {14, 20, 35, 47, 50, 65, 72, 81, 90, 99};
System.out.println("The elements of the array is defined as ");
for (int i : input_array) {
System.out.print(i +" ");
}
int key_element = 72;
System.out.println("\n\nThe elements to be searched in the array is: " + key_element);
int index = recSearch(input_array, 0, input_array.length-1, key_element);
if (index != -1)
System.out.println("\nThe element " + key_element + " is present at position: " + index);
else
System.out.println("Element " + key_element + " is not present: ");
}
}
ผลลัพธ์
The elements of the array is defined as 14 20 35 47 50 65 72 81 90 99 The elements to be searched in the array is: 72 The element 72 is present at position: 6
ตัวอย่างที่ 2: Linear Search บนสตริง
public class Demo {
static int recSearch(String input_array[], int l, int r, String key_element) {
if (r < l)
return -1;
if (input_array[l] == key_element)
return l;
if (input_array[r] == key_element)
return r;
return recSearch(input_array, l+1, r-1, key_element);
}
public static void main(String[] args) {
String input_array[] = { "Scala", "Java", "Python", "Mysql"};
System.out.println("The elements of the array is defined as ");
for (String i : input_array) {
System.out.print(i +" ");
}
String key_element = "Java";
System.out.println("\n\nThe elements to be searched in the array is: " + key_element);
int index = recSearch(input_array, 0, input_array.length-1, key_element);
if (index != -1)
System.out.println("\nThe element " + key_element + " is present at position: " + index);
else
System.out.println("Element " + key_element + " is not present: ");
}
}
ผลลัพธ์
The elements of the array is defined as Scala Java Python Mysql The elements to be searched in the array is: Java The element Java is present at position: 1