Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
Why is it faster to process a sorted array than an unsorted array in C++?
In C++, it is faster to process a sorted array than an unsorted array because of branch prediction. In computer architecture, a branch prediction determines whether a conditional branch (jump) in the instruction flow of a program is likely to be taken or not.
Let’s take an example −
if(arr[i] > 50) {
Do some operation B
} else {
Do some operation A
}
If we run this code for 100 elements in unsorted and sorted order below things will be happened −
For sorted array −
1, 2, 3, 4, 5, …… 50, 51………100 A, A, A, A, A A, B B
It will load the correct branch in the pipeline and correct sequence
A, A, A, A, A, A, A, A A, B B
For unsorted array −
5, 51, 6, 90, 4, 49, 60… A, B, A, B, A, A, A, B
Branch prediction doesn’t play a significant role here. It is very difficult to predict the right operation between A and B.
Advertisements
