
Apex is Salesforce’s backend development language.
While doing development in any programming language, understanding of basic data structure and algorithms helps you organize and process data effectively.
Two fundamental operations are searching (finding an item) and sorting (reordering items).
In this article, we will learn about linear search and a simple sorting algorithm (bubble sort) in plain terms, show Apex code for each, and compare linear search vs binary search for beginners. We’ll also look at real-world examples (like searching a contact list or sorting test scores) to make these ideas clear.
Linear Search vs Binary Search
It’s useful to know when to use linear search and when a faster method like binary search could apply.
The key difference between them is that binary search only works on sorted lists , that means data should be sorted like alphabetically etc.
Binary search operates by iteratively reducing the search range by half in each step, focusing on the portion of the list where the target might reside based on a comparison with the middle element.. If the target is bigger, you search the right half next; if smaller, you search the left half. This way, each step cuts the search space in half.
This way binary search becomes much more efficient when it comes to searching on large lists or data sets but again the data should be sorted before hand.
In contrast, linear search checks items one by one and doesn’t require any sorting.
For example, lets say we have names of all the students studying in class 10th but they are not sorted alphabatically, in this scenario if we want to search for a particular string lets say a name called ‘Harsh Veer’ and lets say this ‘target‘ string, in this scenario linear search will compare each string with the target string i.e ‘Harsh Veer’ and once that string is found it returns us the array index.
Now lets assume, now we have a large list of all the students studying in that particular school, say we have now 1000 names of students and we need to find the target string from that large list. Here if we implement linear search alogoeithm then it will compare each element of that list which will be time consuming and not the efficient way of searching.
In these types of scenarios where we have very large datatset or list, we should prefer binary search.
In short:
- Linear Search:
- Works on any list (sorted or not).
- Simple but can be slow (checks each item) therefore useful in small lists.
- Time Complexity O(n)
- Binary Search:
- Very fast on large, sorted lists (splits list in half each step).
- Doesn’t work if data isn’t sorted.
- Time complexity O(log n)
For beginners, linear search is a great starting point. Learning binary search afterward shows how sorting data first can make searching much faster.
The linear search algorithm offers the simplest mechanism for traversing a list to identify a specific item. As the name suggests, it checks each element one by one until it finds the target. Think of it like scanning through a column of names on your screen from top to bottom.
Linear search utilized an Array data structure where we iterate over all the array elements and compare each element one by one.
If the element is found in the array list , it returns the array index.
Otherwise if the element is not present in the array list , it returns -1′
In other words:
- Start at the first item.
- Compare it to the value you’re looking for. If it matches, stop and return its position/index.
- If not, move to the next item and repeat.
- If you reach the end without a match, the item isn’t in the list and return -1.
For example, imagine a list of contact names: ['Harsh', 'Anu', 'Rahul', 'Simran', 'Akaay' , 'Adi']
, and you want to find "Akaay"
. Linear search would check 'Harsh'
(no), then 'Anu'
(no), then 'Rahul'
(no), then 'Simran'
(no), then 'Akaay'
(yes – stop here).
And if we count how many comparisions were made in order to reach to the target then we will get value as = 5.
Here’s how you could write linear search in Apex, using a loop through a List. We’ll search a simple list of strings for a target name:
public class LinearSearchAlgorithm {
public static Integer linearsearchalgo()
{
List<String> names = new List<String>{'Harsh','Anu','Rahul','Simran','Akaay','Adi'};
String target = 'Akaay';
Integer compare = 0;
Integer foundIndex = -1;
for(Integer i =0; i<= names.size(); i++){
compare++; // to check how many comparison were done to reach to the targeted string
if(names.get(i) == target){ //check if name is equal to out target name
foundIndex = i; // if name is found than update foundIndex with the name position/index;
break;
}
}
System.debug('Found target at index : ' + foundIndex);
System.debug('Number of comparison's done : '+ compare);
return foundIndex;
}
}
In this code, we loop through names
. If names.get(i)
equals the target
, we record foundIndex = i
and exit the loop. If the loop finishes without finding it, foundIndex
stays -1
. This tells us whether (and where) the item was found.
Checkout few examples at geeksforgeeks as well : https://www.geeksforgeeks.org/linear-search/
Real-world example:
Searching a Contact List. Suppose you have a Salesforce Contact list and need to find a person by name. A linear search in Apex would check each contact one by one. While Apex has powerful querying (like SOQL and the List.sort()
method), understanding the manual approach shows the logic behind “looking through” the list.
Sorting with Bubble Sort
Sorting means putting items in order, such as from smallest to largest. One basic sorting algorithm is bubble sort. It’s easy to understand but not very efficient for large lists. In bubble sort, you repeatedly walk through the list and swap any out-of-order adjacent items. Over multiple passes, bigger values “bubble” toward the end of the list.
Figure: Example of the bubble sort process. Each pass moves the largest remaining elements to the right (sorted) side. Bubble sort works like this:
- Compare each pair of neighbors in the list.
- If a pair is out of order (left element > right element), swap them.
- Repeat this process for each element (one full pass).
- After each pass, the largest unsorted element will have moved to its correct place at the end.
- Repeat passes until no more swaps are needed (the list is sorted).
For instance, sorting student test scores. Suppose you have scores [85, 42, 93, 76, 58]
and want them in ascending order. Bubble sort would compare 85 & 42 (swap), then compare 85 & 93 (no swap), and so on, repeatedly passing through the list until it’s fully ordered.
Here’s a simple bubble sort implementation in Apex for a list of integers:
public class BubbleSortAlgorithm {
public static void bubleSort(){
List<Integer> scores = new List<Integer>{85, 2, 93, 6, 58};
for (Integer i = 0; i < scores.size(); i++) {
for (Integer j = 0; j < scores.size() - 1 - i; j++) {
if (scores.get(j) > scores.get(j + 1)) {
// swap scores[j] and scores[j+1]
Integer temp = scores.get(j);
scores.set(j, scores.get(j + 1));
scores.set(j + 1, temp);
}
}
}
System.debug('Sorted scores: ' + scores);
}
}
After this code runs, scores
will be [2, 6, 58, 85, 93]
. In each pass of the outer loop, the inner loop moves the next-largest element into place.
Note: In real Salesforce code, you might just use scores.sort()
or an ORDER BY
in a SOQL query to sort data efficiently. Bubble sort here is for learning.
We have few other ways also to optimize the search but this example is demonstrated for educational purposes.
Real-World Scenarios
- Searching Contacts: In a Salesforce contact list, you might look up a specific person by name. A linear search would check each contact in turn (like going down a roster). If the list is large and sorted by last name, you might use binary search for speed.
- Sorting Student Scores: A teacher wants to rank students by score. Using a sorting algorithm (like bubble sort above), you can reorder the scores from lowest to highest. In Apex, you could also sort a
List<Integer>
of scores. - Organizing Items: You might sort product prices, dates, or any list of values in an application. Understanding basic sorting algorithms helps in cases where custom ordering logic is needed.
By practicing these examples, you see how data structure and algorithm concepts apply in Apex code. These ideas are beginner-friendly and show the logic behind list operations.
Overall, searching and sorting are fundamental. We’ve shown how to implement a linear search and a simple bubble sort in Apex. We also saw why binary search is faster when data is sorted. Keep in mind that Apex provides built-in methods like List.sort()
, but knowing the core algorithms builds your programming skills. As you learn more, you can explore other search/sort methods. Happy coding!
Please feel free to reach me out and requesting you all to let me know if you need help on article on any specific topic. 🙂
Checkout my other articles : https://thetechnologyfiction.com/salesforce-data-loader-a-comprehensive-guide/