C++ Programming Code Examples
C++ > Sorting Searching Code Examples
Program to Find k Numbers Closest to Median of S, Where S is a Set of n Numbers
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
/* Program to Find k Numbers Closest to Median of S, Where S is a Set of n Numbers
- We need to find k numbers which have a minimum difference with the median of the data set.
- It includes sorting using quick sort and then printing k numbers as a result.
- The time complexity will be O(n*log(n)+k).
- Take input of the data.
- Sort the data using the quick-sort algorithm.
- Starting from the median index, using two variable moves towards the end of the array.
- compare each value to the median and print those which are closer to it.
- Repeat this k time printing the k numbers closest to the median.
- 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, i, high, low, k;
double d1,d2, median;
cout<<"Enter the number of element in dataset: ";
cin>>n;
int a[n];
// Taking input of the data set.
for(i = 0; i < n; i++)
{
cout<<"\nEnter "<<i+1<<"th element: ";
cin>>a[i];
}
cout<<"\nEnter the number of element nearest to the median required: ";
cin>>k;
// Sort the data.
QuickSort(a, 0, n-1);
//Print the result.
cout<<"\tThe K element nearest to the median are: ";
// Check the number of data element to be even or odd and proceed accordingly.
if(n%2 == 1)
{
median = a[n/2];
high = n/2+1;
low = n/2;
// Loop to search for the next element generating minimum difference from median.
while(k > 0)
{
// If difference from the first half element is minimum.
if((median-a[low] <= a[high]-median) && low >= 0)
{
cout<<" "<<a[low];
low--;
k--;
}
// If difference from the Second half element is minimum.
else if((median-a[low] > a[high]-median) && high <= n-1)
{
cout<<" "<<a[high];
high++;
k--;
}
}
}
else
{
// Need to use floating variable since the median can be in the fractional form.
d1 = a[n/2];
d2 = a[n/2-1];
median = (d1+d2)/2;
high = n/2;
low = n/2-1;
while(k > 0)
{
d1 = a[low];
d2 = a[high];
// If difference from the first half element is minimum.
if((median-d2 <= d1-median) && low >= 0)
{
cout<<" "<<a[low];
low--;
k--;
}
// If difference from the Second half element is minimum.
else if((median-d2 > d1-median) && high <= n-1)
{
cout<<" "<<a[high];
high++;
k--;
}
}
}
return 0;
}
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.
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:
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.
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.
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.
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).
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.
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.
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.
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.
#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.
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.
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.
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.
A 'function implementing' Binary search on a 'Sorted array'. Every time this function called, counted as a iteration of 'binary search'. So if value is "Less than Value" at start index more
Return a pseudorandom int, and change the internal state. Return a "pseudorandom" int, and change the internal state. does not work. Return a "pseudorandom" double in the open
A Function to build max heap from the initial array by checking all non-leaf node to satisfy the condition. And build "max-heap" k times, extract the 'maximum' and store it in the end