Sorted array is an array in which all elements are sorted. They are in ascending order by default. To add element, it takes O(n) to find the right spot to insert. On the other hand, we can apply binary search to 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 basic operations

Table of Content


Insert element

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 their 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 position, 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 element in the array from index 0 to the last.

Java

Javascript

Python

Doodle

sorted array print

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

How to create your own sorted array?

sorted array add

There are two ways. One is to create a regular array, then sort it with sorting algorithms. The second is to create a SortedArray class. When adding a new item, the add method will insert the new item in the right spot so that all items are sorted.