// BuildLang Standard Library - Sorting Module
// In-place sorting algorithms operating on arrays via references.
/// Swap two elements in an array by index.
fn swap(arr: &mut [i32; 100], i: i32, j: i32) {
let temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
/// Insertion sort - O(n^2) but stable and efficient for small arrays.
fn insertion_sort(arr: &mut [i32; 100], len: i32) {
let mut i: i32 = 1;
while i < len {
let key = arr[i];
let mut j = i - 1;
while j >= 0 && arr[j] > key {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
i = i + 1;
}
}
/// Selection sort - O(n^2), finds minimum and swaps to front.
fn selection_sort(arr: &mut [i32; 100], len: i32) {
let mut i: i32 = 0;
while i < len - 1 {
let mut min_idx = i;
let mut j = i + 1;
while j < len {
if arr[j] < arr[min_idx] {
min_idx = j;
}
j = j + 1;
}
if min_idx != i {
let temp = arr[i];
arr[i] = arr[min_idx];
arr[min_idx] = temp;
}
i = i + 1;
}
}
/// Bubble sort - O(n^2), repeatedly swaps adjacent elements.
fn bubble_sort(arr: &mut [i32; 100], len: i32) {
let mut i: i32 = 0;
while i < len - 1 {
let mut j: i32 = 0;
while j < len - i - 1 {
if arr[j] > arr[j + 1] {
let temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
j = j + 1;
}
i = i + 1;
}
}
/// Check if an array is sorted in ascending order.
fn is_sorted(arr: &[i32; 100], len: i32) -> bool {
let mut i: i32 = 0;
while i < len - 1 {
if arr[i] > arr[i + 1] {
return false;
}
i = i + 1;
}
true
}
/// Binary search - returns index of target, or -1 if not found.
/// Array must be sorted.
fn binary_search(arr: &[i32; 100], len: i32, target: i32) -> i32 {
let mut low: i32 = 0;
let mut high = len - 1;
while low <= high {
let mid = low + (high - low) / 2;
if arr[mid] == target {
return mid;
}
if arr[mid] < target {
low = mid + 1;
} else {
high = mid - 1;
}
}
-1
}