
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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.
- Related Articles
- Why is it faster to process a sorted array than an unsorted array in C++ program?
- Java program to create a sorted merged array of two unsorted arrays
- Find k closest numbers in an unsorted array in C++
- k-th missing element in an unsorted array in C++
- Count pairs in a sorted array whose sum is less than x in C++
- Count pairs in a sorted array whose product is less than k in C++
- Element Appearing More Than 25% In Sorted Array in C++
- Find floor and ceil in an unsorted array using C++.
- C++ program to search an element in a sorted rotated array
- Find the largest pair sum in an unsorted array in C++
- Check if an array is sorted and rotated in C++
- Maximum in an array that can make another array sorted in C++
- Program for Mean and median of an unsorted array in C++
- Print all pairs in an unsorted array with equal sum in C++
- Swift Program to Find Mean of an Unsorted Array

Advertisements