Algorithms: Sort, Search & Find
Algorithmsbeginner~6 min
Use built-in sort and find operations to organise data and locate elements efficiently.
Step 1 — Sort a dataset
sort() returns a sorted copy of the array in ascending order. The original array is unchanged — assign the result to a new variable.
data = [5 3 8 1 9 2 7 4 6]; sorted = sort(data); disp(sorted)▶ Run in SimLab
Expected output: [1, 2, 3, 4, 5, 6, 7, 8, 9]
Step 2 — Search with find()
find() returns the indices where a condition is true. Combine it with logical expressions to locate elements that satisfy any criterion.
sorted = [1 2 3 4 5 6 7 8 9]; idx = find(sorted > 5); disp(idx); disp(sorted(idx))▶ Run in SimLab
Expected output: Indices [6,7,8,9] and values [6,7,8,9]
Step 3 — Binary search via sorting + find()
Combine sort and find to simulate a binary-search workflow: sort once, then query repeatedly.
data = [42 17 88 55 3 73 29];
sorted = sort(data);
target = 55;
pos = find(sorted == target);
printf('Found %d at sorted position %d\n', target, pos)▶ Run in SimLabExpected output: Found 55 at sorted position 5
Related Tutorials
Try SimLab — Free MATLAB® Alternative
466 functions. Runs in your browser. No install.
Open SimLab