A sorted array is an array in which all elements are sorted. They are in ascending order by default. To add an element, it takes O(n) to find the right spot to insert. On the other hand, you can apply binary search to a sorted array to get performance gain from O(n) to O(logn).

sorted array diagram

Map of array implementations

Part 1 – Array implementation
you are here
Part 2 – Sorted array implementation
Part 3 – Matrix 2d array implementation

Table of Content


Insert element in a sorted array

To insert an element in a sorted array, find the index of the position first. Then starting from the end to the index+1, move each element to its next position. Last put the value at the index.

Java

Javascript

Python

Doodle

sorted array insert


Delete element

Starting from the end, move each element one position ahead until the index of the key.

Java

Javascript

Python

Doodle

sorted array delete


Binary search

Given the low and high positions, get the mid position. Compare the value of mid with the key, you can decide the new low and high position. Repeat until you find the key. Return the index of the key.

Java

Javascript

Python

Doodle

binary search


Print elements

Print all elements in the array from index 0 to the last.

Java

Javascript

Python

Doodle

sorted array print


Free download

Download Java, JavaScript and Python code
Data Structures Illustrated Java Book

Why sorting arrays?

sorted array add

When an array is sorted, you can apply binary search to find an element. The time complexity of binary search is O(logn). As n grows to millions and billions, binary search becomes especially fast. Binary search only applies to sorted arrays. So sorting data is usually the preliminary step of fast searching.