Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • C++ Data Types
  • C++ Input/Output
  • C++ Arrays
  • C++ Pointers
  • C++ OOPs
  • C++ STL
  • C++ Interview Questions
  • C++ Programs
  • C++ Cheatsheet
  • C++ MCQ
  • C++ Projects
  • C++ Exception Handling
  • C++ Memory Management
Open In App
Next Article:
How to Find the Median of a Sorted Array in C++?
Next article icon

How to Find the Median of 2D Array in C++?

Last Updated : 14 Feb, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The median can be defined as the middle element of a sorted array in the case of an odd number of elements in an array and the average of the middle two elements when the number of elements in an array is even.

In this article, we will see how to calculate the median of a 2D array in C++.

Example:

Input:  myArray = { {1, 6, 5},                       {2, 4, 6},                      {7, 22, 9} }  Output:  Median is: 5

Finding Median of 2D Array in C++

To find the median of the 2D array, we first have to convert it to a 1D array by placing row after row. After then we will sort it and find the median in that sorted array. This approach is explained below in detail:

Approach

  1.  Create a 1D array with a size equal to the total number of elements in the 2D array.
  2. Traverse the 2D array using nested loops and add each element to flattenedArray.
  3. Sort flattenedArray in ascending order.
  4. If the total number of elements is even, the median is the average of the two middle numbers.
  5. If the total number of elements is odd, the median is the middle number.

C++ Program to Find Median of 2D Array

C++
// C++ program to find the median of a 2D array #include <algorithm> #include <iostream> using namespace std;  // Function to find the median of a 2D array double findMedian(int matrix[3][3], int m, int n) {     int mergedArray[m * n];     int count = 0;      // Merge elements into a 1D array     for (int i = 0; i < m; i++) {         for (int j = 0; j < n; j++) {             mergedArray[count++] = matrix[i][j];         }     }      // Sort the merged array     sort(mergedArray, mergedArray + m * n);      // Calculate the median     if ((m * n) % 2 == 0) {         return (mergedArray[(m * n) / 2 - 1]                 + mergedArray[(m * n) / 2])                / 2.0;     }     else {         return mergedArray[(m * n) / 2];     } }  // Main function int main() {     // Given 2D array     int matrix[3][3]         = { { 1, 6, 5 }, { 2, 4, 6 }, { 7, 22, 9 } };      // Find and display the median     cout << "Median of the 2D array is "          << findMedian(matrix, 3, 3) << endl;     return 0; } 

Output
Median of the 2D array is 6  

Time complexity: O(n*m log(n*m) ) where n is the number of rows and m is the number of columns.
Space complexity: O(n*m)


Next Article
How to Find the Median of a Sorted Array in C++?

A

anushamahajan5
Improve
Article Tags :
  • C++ Programs
  • C++
  • cpp-array
  • CPP Examples
Practice Tags :
  • CPP

Similar Reads

  • How to Find the Median of Array in C++?
    In C++, the array is a collection of elements of the same type, In this article, we will learn how to find the median of the array in C++. The median of the array will be the middle element if the number of elements is odd or the average of two middle elements if the number of elements is even in th
    2 min read
  • How to Find the Median of a Sorted Array in C++?
    In C++, the median of a sorted array is the middle element if the array size is odd, or the average of the two middle elements if the array size is even. In this article, we will learn how to find the median of a sorted array in C++. Example Input: myArray: {1, 2, 3, 4, 5} Output: Median of the Arra
    2 min read
  • How to Find the Mode in a 2D Array in C++?
    A mode is a number that occurs most frequently in comparison to other numbers in a given dataset. In this article, we will find the mode in a 2D array of integers in C++. Input:myArray = { {1, 2, 2, 3}, {3, 4, 5, 5}, {5, 6, 7, 8} }Output: 5Mode in 2D ArrayTo find a mode of numbers in a 2D array, we
    2 min read
  • How to Find the Length of an Array in C++?
    In C++, the length of an array is defined as the total number of elements present in the array. In this article, we will learn how to find the length of an array in C++. The simplest way to find the length of an array is by using the sizeof operator. First calculate the size of the array in bytes an
    2 min read
  • How to Find the Range of Values in a 2D Array in C++?
    In C++, 2D arrays are also known as a matrix, and the range of numbers in a 2D array means the maximum and the minimum value in which the numbers lie in the given 2D array. In this article, we will learn how to find the range of numbers in a 2D array in C++. For Example, Input: my2DArray= {{80, 90,
    2 min read
  • How to Find the Mode in a Sorted Array in C++?
    The mode of the given numbers can be defined as the value that occurs the most in the given dataset or the value with the highest frequency. In this article, we will discuss how to calculate the mode of the numbers in a sorted array in C++. Example: Input: myVector = {1, 2, 2, 3, 3, 3, 4, 4, 5} Outp
    3 min read
  • How to Find the Mode of Numbers in an Array in C++?
    Mode of any dataset is the item that occurs most frequently in it. In this article, we will find the mode of numbers in an unsorted array in C++. For Example,Input: myArray = { 1, 2, 3, 4, 5, 2, 3, 2, 2, 4, 2 } Output: Mode : 2Finding Mode of Array Elements in C++To find the mode of the array elemen
    2 min read
  • How to Find the Variance of Numbers in 2D Array in C++?
    The variance of numbers is a measure of the spread of a set of values which is used to find how much the values in a dataset differ from mean or average. In this article, we will learn how to find the variance of numbers in a 2D array in C++. Example Input: myMatrix = { { 10, 20, 30 }, { 40, 50, 60
    3 min read
  • How to Find the Sum of Elements in an Array in C++?
    In C++, an array is the collection of similar data elements that are stored in the contiguous memory location and we can access these elements directly by their index value. In this article, we will learn how to find the sum of elements in an array in C++. Example:Input: myVector = {1, 2, 3, 4, 5} O
    2 min read
  • How to Find the Range of Numbers in an Array in C++?
    The range of numbers in an array means the difference between the maximum value and the minimum value in the given array. In this article, we will learn how to find the range of numbers in an array in C++. For Example, Input: myArray = {5,10,15,30,25}; Output: Range: 25Range Within an Array in C++To
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences