You can sort a list without using the built-in sort method by implementing a sorting algorithm yourself, such as bubble sort, selection sort, or insertion sort. The most common mistake is trying to write a custom sort but accidentally mutating the original list or using a comparison that doesn’t handle all cases. The key is to choose an algorithm that fits your data size and to understand how it compares elements.
Pick an Algorithm That Fits Your Data
For small lists (under a few hundred items), a simple O(n²) algorithm like bubble sort or insertion sort is fine and easy to write. For larger lists, you’d want something like merge sort or quicksort, but those are more complex. Since you’re avoiding sort, you’re likely doing this for a learning exercise or a coding interview, so start with the simplest correct version.
Here are the three most common manual sorts:
| Algorithm | Time Complexity | Space | Best For |
|---|---|---|---|
| Bubble sort | O(n²) | O(1) | Teaching, tiny lists |
| Selection sort | O(n²) | O(1) | Simple, few swaps |
| Insertion sort | O(n²) average, O(n) nearly sorted | O(1) | Small or nearly sorted lists |
Rule of thumb: if your list has fewer than 50 items, any of these will be fast enough. If it’s larger, consider merge sort (O(n log n)) but be ready to handle extra memory.
Write Bubble Sort Step by Step
Bubble sort is the easiest to remember: repeatedly step through the list, compare adjacent elements, and swap them if they’re in the wrong order. Repeat until no swaps are needed.
- Start at the first element. Compare it with the next.
- If the first is greater than the second, swap them.
- Move to the next pair and repeat to the end. The largest element will ‘bubble’ to the end.
- Repeat the whole pass, but ignore the last sorted element each time.
- Stop when a full pass makes no swaps.
Here’s a generic implementation (pseudocode, but you can adapt to any language):
for i from 0 to n-1:
swapped = false
for j from 0 to n-i-2:
if list[j] > list[j+1]:
swap(list[j], list[j+1])
swapped = true
if not swapped: break
This works in-place, so it doesn’t create a new list. If you need to keep the original list unchanged, copy it first with list.copy() or slice().
Try Selection Sort for Fewer Swaps
Selection sort finds the smallest element and puts it at the front, then finds the next smallest, and so on. It does fewer swaps than bubble sort (at most n swaps) but the same number of comparisons.
- Find the minimum element in the unsorted part.
- Swap it with the first element of the unsorted part.
- Move the boundary one step forward.
- Repeat until the whole list is sorted.
for i from 0 to n-1:
min_idx = i
for j from i+1 to n-1:
if list[j] < list[min_idx]:
min_idx = j
swap(list[i], list[min_idx])
This is stable only if you implement the swap carefully; otherwise it can reorder equal elements. For most learning purposes, that's fine.
Use Insertion Sort for Nearly Sorted Lists
Insertion sort builds the sorted list one element at a time by taking each new element and inserting it into its correct position among the already sorted elements. It's very efficient for small or nearly sorted lists.
- Start with the second element as the 'key'.
- Compare it with elements to its left, shifting them right if they are larger.
- Insert the key into the gap.
- Move to the next element and repeat.
for i from 1 to n-1:
key = list[i]
j = i-1
while j >= 0 and list[j] > key:
list[j+1] = list[j]
j -= 1
list[j+1] = key
This is stable and works well when the list is already mostly sorted.
Where People Go Wrong
The most common bug is an off-by-one error in the inner loop, causing the last element to be missed or an index out of bounds. Another frequent mistake is comparing elements but not swapping them correctly, especially in languages without tuple assignment. Also, forgetting to break out of the outer loop in bubble sort when no swaps occur leads to unnecessary work.
Another big issue is modifying the list while iterating over it without a copy. If you need the original list intact, always make a copy first. Also, be careful with negative numbers and strings: the comparison operators work the same, but make sure you're comparing the right data type.
For strings, the default lexicographic order is usually what you want, but if you need case-insensitive sorting, convert to lowercase before comparing.
Test Your Sort on Real Cases
Before trusting your sort, test it on a few lists: an empty list, a single element, a list already sorted, a reverse-sorted list, and a list with duplicates. Also test with negative numbers and strings. A simple way to verify is to compare your result with the built-in sorted() function (which returns a new list) on a copy.
If you're writing in a language like Python or JavaScript, you can also use a manual merge sort for larger lists, but that's more advanced. For now, the three above cover most needs.
Sorting Large Lists and Other Languages
If your list is huge (thousands of elements), the O(n²) algorithms will be slow. In that case, implement merge sort or quicksort. Merge sort is easier to write recursively: split the list in half, sort each half, then merge. Quicksort picks a pivot and partitions, but beware of worst-case O(n²) on already sorted lists unless you randomize the pivot.
In languages like C or Java, you'd write similar loops but with explicit index management. The logic is the same; only syntax differs.
Remember, the built-in sort is almost always faster and more reliable. Manual sorting is for learning or when you need a custom order (like sorting by a specific attribute). If you need a custom order, you can often pass a comparator function to the built-in sort, but if you must avoid it, adapt the comparison inside your algorithm.
Sorting Numbers, Strings, and Objects
For numbers, use < and >. For strings, the same works, but be aware of case sensitivity. For objects, you need to define what 'less than' means—for example, sort by a property like age or name. In your inner loop, replace the comparison with something like list[j].age > list[j+1].age.
If you want to sort in descending order, just reverse the comparison operator (e.g., > instead of <).
Related
What to Do Next
After you have a working manual sort, practice by timing it against the built-in sort on a list of 10,000 random numbers. You'll see the difference. Then try to optimize—for example, add a flag to bubble sort to break early, or use a gap sequence for shell sort. But for most purposes, the simple versions are enough.
If you're preparing for an interview, be ready to explain the time and space complexity of your chosen algorithm and why you picked it.