Binary search in a sorted vector
def binary_search(values: vector int, needle: int): int {
let count: uint = length(values) as uint;
let low: mutable int = 0;
let high: mutable int = count as int;
high := high - 1;
while (low <= high) {
let distance: int = high - low;
let mid: int = low + (distance / 2);
let index: uint = mid as uint;
let value: int = values[index];
if (value == needle) { return mid; };
if (value < needle) {
low := mid + 1;
} else {
high := mid - 1;
};
}
return 0 - 1;
}
def search_case(needle: int): int {
let values: vector int = [2, 5, 8, 13, 21, 34, 55, 89, 144];
return binary_search(values, needle);
}
def main(): int {
return search_case(55);
}عرف بحث_ثنائي(القيم: متجه عدد, المطلوب: عدد): عدد {
دع العدد: طبيعي = الطول(القيم) مثل طبيعي;
دع الأدنى: متغير عدد = 0;
دع الأعلى: متغير عدد = العدد مثل عدد;
الأعلى := الأعلى - 1;
طالما (الأدنى <= الأعلى) {
دع المسافة: عدد = الأعلى - الأدنى;
دع الوسط: عدد = الأدنى + (المسافة / 2);
دع الموضع: طبيعي = الوسط مثل طبيعي;
دع القيمة: عدد = القيم[الموضع];
إذا (القيمة == المطلوب) { أرجع الوسط; };
إذا (القيمة < المطلوب) {
الأدنى := الوسط + 1;
} وإلا {
الأعلى := الوسط - 1;
};
}
أرجع 0 - 1;
}
عرف حالة_بحث(المطلوب: عدد): عدد {
دع القيم: متجه عدد = [2, 5, 8, 13, 21, 34, 55, 89, 144];
أرجع بحث_ثنائي(القيم, المطلوب);
}
عرف الرئيسية(): عدد {
أرجع حالة_بحث(55);
}
Run it
With the interpreter, without compiling:
./build/sultanc run examples/en/algorithms/binary_search.snOr compile it to an executable:
./build/sultanc examples/en/algorithms/binary_search.sn -o build/example && ./build/example