
- 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++ program?
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 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 its 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++?
- Java program to create a sorted merged array of two unsorted arrays
- C++ program to search an element in a sorted rotated array
- Program for Mean and median of an unsorted array in C++
- Swift Program to Find Mean of an Unsorted Array
- Swift Program to Find Median of an Unsorted Array
- C++ Program to Implement Sorted Array
- Java Program to sort integers in unsorted array
- 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++.
- Write a Golang program to search an element in a sorted array

Advertisements