'phoosana', on 25 Oct 2012 - 09:38, said:
ครับ ที่ถามเผื่อยังไม่มี ถ้ามีอะไรสงสัยก็ถามมาได้ หรือหลังไมล์มาก็ได้ครับ
มีปัญหา มาถามอีกแล้วครับ ท่าน phoosana
อยากถามเกี่ยวกับ การใช้ method ภายใน method ของตัวเอง
หรือ จะเรียก อีกนัยหนึ่งคือ method ซ้อนกัน ไม่รู้จบ (อันนี้ผมตั้งด้วยความเข้าใจตัวเองครับ)
จากตัวอย่างนะครับ
public class MergeSort
{
private int a[];
public MergeSort(int b[])
{
a = b;
}
public void
sort()
{ if(a.length <= 1)
return;
int first[] = new int[a.length / 2];
int second[] = new int[a.length - first.length];
for(int x = 0; x < first.length; x++)
first[x] = a[x];
for(int x = first.length, y = 0; x < a.length; x++, y++)
first[y] = a[x];
//Split the array again MergeSort sort1 = new MergeSort(first);
MergeSort sort2 = new MergeSort(second); sort1.
sort();
sort2.
sort();
merge(first, second);
} private void
merge(int first[], int second[])
{
int x = 0;
int y = 0;
int z = 0;
while(x < first.length && y < second.length)
{
if(first[x] < second[y])
{
a[z] = first[x];
x++;
}
else
{
a[z] = second[y];
y++;
}
z++;
}
//copy remaining elements to the tail of a[]; for(int i = x; i < first.length; i++)
{
a[z] = first[i];
z++;
}
for(int i = y; i < second.length; i++)
{
a[z] = second[i];
z++;
}
}
}
จาก code นี้ ตามความเข้าใจของผมคือ ถ้า method ตัวเอง ถูกเรียกใช้ภายในตัวเอง จะทำให้เกิดการซ้อน ของ method ไม่รู้จบ ใช่หรือไม่ครับ ดูจากกรณีนี้คือ การ sort เป็นคู่ ๆ แต่ใช้คำสั่ง แบ่งแค่ครั้งเดียว และให้ method ซ้อนตัวเองไปเรื่อย ๆ เพื่อทำการ แบ่งซอยย่อยไปเรื่อย ๆ (split array again and again...) ให้สุดท้าย เหลือ element เดี่ยว ๆ
แล้ว คำสั่ง merge ที่ถูกเรียกมาใช้ใน method sort ก็จะทำงาน ซ้อนไปเรื่อย ๆ พร้อม ๆ กันด้วย ใช่หรือไม่ครับ
ผมคิดแบบนี้ ไม่ทราบว่า เข้าใจถูกหรือเปล่าครับ
และการซ้อนกัน ของ method ก็จำเป็น ต้องใช้
constructor เป็นตัวช่วย เพื่อจะทำให้ object ที่สร้างใหม่อยู่ภายใน method นั้น สามารถเรียก method ตัวเองได้ด้วย ใช่หรือไม่ครับ
หรือว่า
constructor นั้น ทำเพื่อเชื่อม private int a[] กับ method sort เท่านั้น
Edited by ทรงธรรม, 29 ตุลาคม พ.ศ. 2555 - 13:53.
ขอให้พวกเรา ชาวหลากสี และพันธมิตร จงมีชีวิตรอด จากภาวะเศรษฐกิจตกต่ำ ฝีมือปูนา ไปตลอดรอดฝั่งด้วยครับ
PEMDAS ย่อมาจาก ลำดับการคำนวณ Parentheses , Exponentials , Multiply , Divide , Add , Subtract
FWGHSO ย่อมาจาก ลำดับการประเมินผลของ query FROM, WHERE, GROUP BY, HAVING, SELECT, ORDER BY