Happy Codings - Programming Code Examples
Html Css Web Design Sample Codes CPlusPlus Programming Sample Codes JavaScript Programming Sample Codes C Programming Sample Codes CSharp Programming Sample Codes Java Programming Sample Codes Php Programming Sample Codes Visual Basic Programming Sample Codes


C++ Programming Code Examples

C++ > Sorting Searching Code Examples

C++ Program to Find Median of Two Sorted Arrays

/* C++ Program to Find Median of Two Sorted Arrays This is a C++ Program find the median of elements where elements are stored in 2 different arrays. - We need to find combined median of two different data set. - It includes sorting of both arrays using quick sort and then printing the median by simultaneously traversing both arrays. - The time complexity will be O(n*log(n)+m*log(m)+m+n). - Take input of both the data set of length m and n respectively. - Sort the data sets using the quick-sort algorithm. - Calculate the median, considering both arrays as a single array. - Exit. */ #include<iostream> using namespace std; // Swapping two values. void swap(int *a, int *b) { int temp; temp = *a; *a = *b; *b = temp; } // Partitioning the array on the basis of values at high as pivot value. int Partition(int a[], int low, int high) { int pivot, index, i; index = low; pivot = high; // Getting index of pivot. for(i=low; i < high; i++) { if(a[i] < a[pivot]) { swap(&a[i], &a[index]); index++; } } // Swapping value at high and at the index obtained. swap(&a[pivot], &a[index]); return index; } // Implementing QuickSort algorithm. int QuickSort(int a[], int low, int high) { int pindex; if(low < high) { // Partitioning array using randomized pivot. pindex = Partition(a, low, high); // Recursively implementing QuickSort. QuickSort(a, low, pindex-1); QuickSort(a, pindex+1, high); } return 0; } int main() { int n, m, bi, ai, i, k; double median; cout<<"Enter the number of element in the first data set: "; cin>>n; int a[n]; // Take input of first sequence. for(i = 0; i < n; i++) { cout<<"Enter "<<i+1<<"th element: "; cin>>a[i]; } cout<<"\nEnter the number of element in the second data set: "; cin>>m; int b[m]; // Take input of second sequence. for(i = 0; i < m; i++) { cout<<"Enter "<<i+1<<"th element: "; cin>>b[i]; } // Sort the data of both arrays. QuickSort(a, 0, n-1); QuickSort(b, 0, m-1); //Print the result. cout<<"\tThe Median from these data set is: "; ai = 0; bi = 0; // If the m+n is odd then one median will be there otherwise average of two will be taken as median. if((m+n)%2 == 1) { // K is the number of element present upto the median from the beginning of the data array. k =(n+m)/2+1; while(k > 0) { // Compare current element of array 'a' and 'b' and skip next the smaller one. if(a[ai] <= b[bi] && ai < n) { k--; // Print if we have skipped k element. if(k == 0) cout<<a[ai]; ai++; } else if(a[ai] > b[bi] && bi < m) { k--; // Print if we have skipped k element. if(k == 0) cout<<b[bi]; bi++; } } } else { k = (n+m)/2+1; while(k > 0) { // Compare current element of array 'a' and 'b' and skip next the smaller one. if(a[ai] <= b[bi] && ai < n) { k--; // Add the last two numbers so as we can calculate average. if(k <= 1) median += a[ai]; ai++; } else if(a[ai] > b[bi] && bi < m) { k--; // Add the last two numbers so as we can calculate average. if(k <= 1) median += b[bi]; bi++; } } // Take average. cout<<median/2; } }

A relational operator is used to check the relationship between two operands. C++ Relational Operators are used to relate or compare given operands. Relational operations are like checking if two operands are equal or not equal, greater or lesser, etc. Relational Operators are also called Comparison Operators.

Consider a situation, when we have two persons with the same name, jhon, in the same class. Whenever we need to differentiate them definitely we would have to use some additional information along with their name, like either the area, if they live in different area or their mother's or father's name, etc. Same situation can arise in your C++ applications. For example, you might be writing some code that has a function called xyz() and there is another library available which is also having same function xyz(). Now the compiler has no way of knowing which version of xyz() function you are referring to within your code.

The if...else statement executes two different codes depending upon whether the test expression is true or false. Sometimes, a choice has to be made from more than 2 possibilities. The if...else ladder allows you to check between multiple test expressions and execute different statements. In C/C++ if-else-if ladder helps user decide from among multiple options. The C/C++ if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the C else-if ladder is bypassed. If none of the conditions is true, then the final else statement will be executed.

The cin object is used to accept input from the standard input device i.e. keyboard. It is defined in the iostream header file. C++ cin statement is the instance of the class istream and is used to read input from the standard input device which is usually a keyboard. The extraction operator(>>) is used along with the object cin for reading inputs. The extraction operator extracts the data from the object cin which is entered using the keyboard. The "c" in cin refers to "character" and "in" means "input". Hence cin means "character input". The cin object is used along with the extraction operator >> in order to receive a stream of characters.

#include is a way of including a standard or user-defined file in the program and is mostly written at the beginning of any C/C++ program. This directive is read by the preprocessor and orders it to insert the content of a user-defined or system header file into the following program. These files are mainly imported from an outside source into the current program. The process of importing such files that might be system-defined or user-defined is known as File Inclusion. This type of preprocessor directive tells the compiler to include a file in the source code program.

In computer programming, loops are used to repeat a block of code. For example, when you are displaying number from 1 to 100 you may want set the value of a variable to 1 and display it 100 times, increasing its value by 1 on each loop iteration. When you know exactly how many times you want to loop through a block of code, use the for loop instead of a while loop. A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times.

An array is defined as the collection of similar type of data items stored at contiguous memory locations. Arrays are the derived data type in C++ programming language which can store the primitive type of data such as int, char, double, float, etc. It also has the capability to store the collection of derived data types, such as pointers, structure, etc. The array is the simplest data structure where each data element can be randomly accessed by using its index number. C++ array is beneficial if you have to store similar elements. For example, if we want to store the marks of a student in 6 subjects, then we don't need to define different variables for the marks in the different subject. Instead of that, we can define an array which can store the marks in each subject at the contiguous memory locations.

A program shall contain a global function named main, which is the designated start of the program in hosted environment. main() function is the entry point of any C++ program. It is the point at which execution of program is started. When a C++ program is executed, the execution control goes directly to the main() function. Every C++ program have a main() function.

Logical Operators are used to compare and connect two or more expressions or variables, such that the value of the expression is completely dependent on the original expression or value or variable. We use logical operators to check whether an expression is true or false. If the expression is true, it returns 1 whereas if the expression is false, it returns 0. Assume variable A holds 1 and variable B holds 0:

Compute natural logarithm. Returns the natural logarithm of x. The natural logarithm is the base-e logarithm: the inverse of the natural exponential function (exp). For common (base-10) logarithms, see log10. The C/C++ library function double log(double x) returns the natural logarithm (base-e logarithm) of x. Function returns natural logarithm of x. If x is negative, it causes a domain error. If x is zero, it may cause a pole error (depending on the library implementation).

As the name already suggests, these operators help in assigning values to variables. These operators help us in allocating a particular value to the operands. The main simple assignment operator is '='. We have to be sure that both the left and right sides of the operator must have the same data type. We have different levels of operators. Assignment operators are used to assign the value, variable and function to another variable. Assignment operators in C are some of the C Programming Operator, which are useful to assign the values to the declared variables. Let's discuss the various types of the assignment operators such as =, +=, -=, /=, *= and %=. The following table lists the assignment operators supported by the C language:

In while loop, condition is evaluated first and if it returns true then the statements inside while loop execute, this happens repeatedly until the condition returns false. When condition returns false, the control comes out of loop and jumps to the next statement in the program after while loop. The important point to note when using while loop is that we need to use increment or decrement statement inside while loop so that the loop variable gets changed on each iteration, and at some point condition returns false. This way we can end the execution of while loop otherwise the loop would execute indefinitely. A while loop that never stops is said to be the infinite while loop, when we give the condition in such a way so that it never returns false, then the loops becomes infinite and repeats itself indefinitely.

The cout is a predefined object of ostream class. It is connected with the standard output device, which is usually a display screen. The cout is used in conjunction with stream insertion operator (<<) to display the output on a console. On most program environments, the standard output by default is the screen, and the C++ stream object defined to access it is cout. The "c" in cout refers to "character" and "out" means "output". Hence cout means "character output". The cout object is used along with the insertion operator << in order to display a stream of characters.

Partition range in two. Rearranges the elements from the range [first,last), in such a way that all the elements for which pred returns true precede all those for which it returns false. The iterator returned points to the first element of the second group. The relative ordering within each group is not necessarily the same as before the call. See stable_partition for a function with a similar behavior but with stable ordering within each group. The function shall not modify its argument. This can either be a function pointer or a function object. Function returns an iterator that points to the first element of the second group of elements (those for which pred returns false), or last if this group is empty.

In computer programming, we use the if statement to run a block code only when a certain condition is met. An if statement can be followed by an optional else statement, which executes when the boolean expression is false. There are three forms of if...else statements in C++: • if statement, • if...else statement, • if...else if...else statement, The if statement evaluates the condition inside the parentheses ( ). If the condition evaluates to true, the code inside the body of if is executed. If the condition evaluates to false, the code inside the body of if is skipped.











Palindrome number is a number that remains the same when its digits are reversed. 16461, for example: we take 121 and reverse it, after revers it is same as original. Get a value from