C++ Programming Code Examples
C++ > Data Structures and Algorithm Analysis in C++ Code Examples
A collection of sorting and selection routines
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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
/* A collection of sorting and selection routines */
#ifndef SORT_H_
#define SORT_H_
#define merge Merge
#define swap Swap
/**
* Several sorting routines.
* Arrays are rearranged with smallest item first.
*/
#include "vector.h"
/**
* Simple insertion sort.
*/
template <class Comparable>
void insertionSort( vector<Comparable> & a )
{
/* 1*/ for( int p = 1; p < a.size( ); p++ )
{
/* 2*/ Comparable tmp = a[ p ];
int j;
/* 3*/ for( j = p; j > 0 && tmp < a[ j - 1 ]; j-- )
/* 4*/ a[ j ] = a[ j - 1 ];
/* 5*/ a[ j ] = tmp;
}
}
/**
* Shellsort, using Shell's (poor) increments.
*/
template <class Comparable>
void shellsort( vector<Comparable> & a )
{
for( int gap = a.size( ) / 2; gap > 0; gap /= 2 )
for( int i = gap; i < a.size( ); i++ )
{
Comparable tmp = a[ i ];
int j = i;
for( ; j >= gap && tmp < a[ j - gap ]; j -= gap )
a[ j ] = a[ j - gap ];
a[ j ] = tmp;
}
}
/**
* Standard heapsort.
*/
template <class Comparable>
void heapsort( vector<Comparable> & a )
{
/* 1*/ for( int i = a.size( ) / 2; i >= 0; i-- ) /* buildHeap */
/* 2*/ percDown( a, i, a.size( ) );
/* 3*/ for( int j = a.size( ) - 1; j > 0; j-- )
{
/* 4*/ swap( a[ 0 ], a[ j ] ); /* deleteMax */
/* 5*/ percDown( a, 0, j );
}
}
/**
* Internal method for heapsort.
* i is the index of an item in the heap.
* Returns the index of the left child.
*/
inline int leftChild( int i )
{
return 2 * i + 1;
}
/**
* Internal method for heapsort that is used in
* deleteMax and buildHeap.
* i is the position from which to percolate down.
* n is the logical size of the binary heap.
*/
template <class Comparable>
void percDown( vector<Comparable> & a, int i, int n )
{
int child;
Comparable tmp;
/* 1*/ for( tmp = a[ i ]; leftChild( i ) < n; i = child )
{
/* 2*/ child = leftChild( i );
/* 3*/ if( child != n - 1 && a[ child ] < a[ child + 1 ] )
/* 4*/ child++;
/* 5*/ if( tmp < a[ child ] )
/* 6*/ a[ i ] = a[ child ];
else
/* 7*/ break;
}
/* 8*/ a[ i ] = tmp;
}
/**
* Mergesort algorithm (driver).
*/
template <class Comparable>
void mergeSort( vector<Comparable> & a )
{
vector<Comparable> tmpArray( a.size( ) );
mergeSort( a, tmpArray, 0, a.size( ) - 1 );
}
/**
* Internal method that makes recursive calls.
* a is an array of Comparable items.
* tmpArray is an array to place the merged result.
* left is the left-most index of the subarray.
* right is the right-most index of the subarray.
*/
template <class Comparable>
void mergeSort( vector<Comparable> & a,
vector<Comparable> & tmpArray, int left, int right )
{
if( left < right )
{
int center = ( left + right ) / 2;
mergeSort( a, tmpArray, left, center );
mergeSort( a, tmpArray, center + 1, right );
merge( a, tmpArray, left, center + 1, right );
}
}
/**
* Internal method that merges two sorted halves of a subarray.
* a is an array of Comparable items.
* tmpArray is an array to place the merged result.
* leftPos is the left-most index of the subarray.
* rightPos is the index of the start of the second half.
* rightEnd is the right-most index of the subarray.
*/
template <class Comparable>
void merge( vector<Comparable> & a, vector<Comparable> & tmpArray,
int leftPos, int rightPos, int rightEnd )
{
int leftEnd = rightPos - 1;
int tmpPos = leftPos;
int numElements = rightEnd - leftPos + 1;
// Main loop
while( leftPos <= leftEnd && rightPos <= rightEnd )
if( a[ leftPos ] <= a[ rightPos ] )
tmpArray[ tmpPos++ ] = a[ leftPos++ ];
else
tmpArray[ tmpPos++ ] = a[ rightPos++ ];
while( leftPos <= leftEnd ) // Copy rest of first half
tmpArray[ tmpPos++ ] = a[ leftPos++ ];
while( rightPos <= rightEnd ) // Copy rest of right half
tmpArray[ tmpPos++ ] = a[ rightPos++ ];
// Copy tmpArray back
for( int i = 0; i < numElements; i++, rightEnd-- )
a[ rightEnd ] = tmpArray[ rightEnd ];
}
/**
* Quicksort algorithm (driver).
*/
template <class Comparable>
void quicksort( vector<Comparable> & a )
{
quicksort( a, 0, a.size( ) - 1 );
}
/**
* Standard swap
*/
template <class Comparable>
inline void swap( Comparable & obj1, Comparable & obj2 )
{
Comparable tmp = obj1;
obj1 = obj2;
obj2 = tmp;
}
/**
* Return median of left, center, and right.
* Order these and hide the pivot.
*/
template <class Comparable>
const Comparable & median3( vector<Comparable> & a, int left, int right )
{
int center = ( left + right ) / 2;
if( a[ center ] < a[ left ] )
swap( a[ left ], a[ center ] );
if( a[ right ] < a[ left ] )
swap( a[ left ], a[ right ] );
if( a[ right ] < a[ center ] )
swap( a[ center ], a[ right ] );
// Place pivot at position right - 1
swap( a[ center ], a[ right - 1 ] );
return a[ right - 1 ];
}
/**
* Internal quicksort method that makes recursive calls.
* Uses median-of-three partitioning and a cutoff of 10.
* a is an array of Comparable items.
* left is the left-most index of the subarray.
* right is the right-most index of the subarray.
*/
template <class Comparable>
void quicksort( vector<Comparable> & a, int left, int right )
{
/* 1*/ if( left + 10 <= right )
{
/* 2*/ Comparable pivot = median3( a, left, right );
// Begin partitioning
/* 3*/ int i = left, j = right - 1;
/* 4*/ for( ; ; )
{
/* 5*/ while( a[ ++i ] < pivot ) { }
/* 6*/ while( pivot < a[ --j ] ) { }
/* 7*/ if( i < j )
/* 8*/ swap( a[ i ], a[ j ] );
else
/* 9*/ break;
}
/*10*/ swap( a[ i ], a[ right - 1 ] ); // Restore pivot
/*11*/ quicksort( a, left, i - 1 ); // Sort small elements
/*12*/ quicksort( a, i + 1, right ); // Sort large elements
}
else // Do an insertion sort on the subarray
/*13*/ insertionSort( a, left, right );
}
/**
* Internal insertion sort routine for subarrays
* that is used by quicksort.
* a is an array of Comparable items.
* left is the left-most index of the subarray.
* right is the right-most index of the subarray.
*/
template <class Comparable>
void insertionSort( vector<Comparable> & a, int left, int right )
{
for( int p = left + 1; p <= right; p++ )
{
Comparable tmp = a[ p ];
int j;
for( j = p; j > left && tmp < a[ j - 1 ]; j-- )
a[ j ] = a[ j - 1 ];
a[ j ] = tmp;
}
}
/**
* Quick selection algorithm.
* Places the kth smallest item in a[k-1].
* a is an array of Comparable items.
* k is the desired rank (1 is minimum) in the entire array.
*/
template <class Comparable>
void quickSelect( vector<Comparable> & a, int k )
{
quickSelect( a, 0, a.size( ) - 1, k );
}
/**
* Internal selection method that makes recursive calls.
* Uses median-of-three partitioning and a cutoff of 10.
* Places the kth smallest item in a[k-1].
* a is an array of Comparable items.
* left is the left-most index of the subarray.
* right is the right-most index of the subarray.
* k is the desired rank (1 is minimum) in the entire array.
*/
template <class Comparable>
void quickSelect( vector<Comparable> & a, int left, int right, int k )
{
/* 1*/ if( left + 10 <= right )
{
/* 2*/ Comparable pivot = median3( a, left, right );
// Begin partitioning
/* 3*/ int i = left, j = right - 1;
/* 4*/ for( ; ; )
{
/* 5*/ while( a[ ++i ] < pivot ) { }
/* 6*/ while( pivot < a[ --j ] ) { }
/* 7*/ if( i < j )
/* 8*/ swap( a[ i ], a[ j ] );
else
/* 9*/ break;
}
/*10*/ swap( a[ i ], a[ right - 1 ] ); // Restore pivot
// Recurse; only this part changes
/*11*/ if( k <= i )
/*12*/ quickSelect( a, left, i - 1, k );
/*13*/ else if( k > i + 1 )
/*14*/ quickSelect( a, i + 1, right, k );
}
else // Do an insertion sort on the subarray
/*15*/ insertionSort( a, left, right );
}
/**
* Class that wraps a pointer variable.
*/
template <class Comparable>
class Pointer
{
public:
Pointer( Comparable *rhs = NULL ) : pointee( rhs ) { }
bool operator<( const Pointer & rhs ) const
{ return *pointee < *rhs.pointee; }
operator Comparable * ( ) const
{ return pointee; }
private:
Comparable *pointee;
};
/**
* Sort objects -- even large ones --
* with only N + ln N Comparable moves on average.
*/
template <class Comparable>
void largeObjectSort( vector<Comparable> & a )
{
vector<Pointer<Comparable> > p( a.size( ) );
int i, j, nextj;
for( i = 0; i < a.size( ); i++ )
p[ i ] = &a[ i ];
quicksort( p );
// Shuffle items in place
for( i = 0; i < a.size( ); i++ )
if( p[ i ] != &a[ i ] )
{
Comparable tmp = a[ i ];
for( j = i; p[ j ] != &a[ i ]; j = nextj )
{
nextj = p[ j ] - &a[ 0 ];
a[ j ] = *p[ j ];
p[ j ] = &a[ j ];
}
a[ j ] = tmp;
p[ j ] = &a[ j ];
}
}
#endif
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:
Access element. Returns a reference to the element at position n in the vector container. A similar member function, vector::at, has the same behavior as this operator function, except that vector::at is bound-checked and signals if the requested position is out of range by throwing an out_of_range exception. Portable programs should never call this function with an argument n that is out of range, since this causes undefined behavior. Function returns the element at the specified position in the vector.
In the C++ Programming Language, the #define directive allows the definition of macros within your source code. These macro definitions allow constant values to be declared for use throughout your code. Macro definitions are not variables and cannot be changed by your program code like variables. You generally use this syntax when creating constants that represent numbers, strings or expressions. The syntax for creating a constant using #define in the C++ is: #define token value
The function in C++ language is also known as procedure or subroutine in other programming languages. To perform any task, we can create function. A function can be called many times. It provides modularity and code reusability. Functions are used to provide modularity to a program. Creating an application using function makes it easier to understand, edit, check... Function declaration, is done to tell the compiler about the existence of the function. Function's return type, its name & parameter list is mentioned. Function body is written in its definition. Functions are called by their names. If the function is without argument, it can be called directly using its name. But for functions with arguments, we have two ways to call them:
Inline function is one of the important feature of C++. So, let's first understand why inline functions are used and what is the purpose of inline function? When the program executes the function call instruction the CPU stores the memory address of the instruction following the function call, copies the arguments of the function on the stack and finally transfers control to the specified function. The CPU then executes the function code, stores the function return value in a predefined memory location/register and returns control to the calling function. This can become overhead if the execution time of function is less than the switching time from the caller function to called function (callee). For functions that are large and/or perform complex tasks, the overhead of the function call is usually insignificant compared to the amount of time the function takes to run. However, for small, commonly-used functions, the time needed to make the function call is often a lot more than the time needed to actually
In C++, constructor is a special method which is invoked automatically at the time of object creation. It is used to initialize the data members of new object generally. The constructor in C++ has the same name as class or structure. Constructors are special class functions which performs initialization of every object. The Compiler calls the Constructor whenever an object is created. Constructors initialize values to object members after storage is allocated to the object. Whereas, Destructor on the other hand is used to destroy the class object. • Default Constructor: A constructor which has no argument is known as default constructor. It is invoked at the time of creating object.
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.
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:
Templates are powerful features of C++ which allows us to write generic programs. Similar to function templates, we can use class templates to create a single class to work with different data types. Class templates come in handy as they can make our code shorter and more manageable. A class template starts with the keyword template followed by template parameter(s) inside <> which is followed by the class declaration. T is the template argument which is a placeholder for the data type used, and class is a keyword. Inside the class body, a member variable var and a member function functionName() are both of type T.
The main purpose of C++ programming is to add object orientation to the C programming language and classes are the central feature of C++ that supports object-oriented programming and are often called user-defined types. A class is used to specify the form of an object and it combines data representation and methods for manipulating that data into one neat package. The data and functions within a class are called members of the class.
C supports nesting of loops in C. Nesting of loops is the feature in C that allows the looping of statements inside another loop. Any number of loops can be defined inside another loop, i.e., there is no restriction for defining any number of loops. The nesting level can be defined at n times. You can define any type of loop inside another loop; for example, you can define 'while' loop inside a 'for' loop. A loop inside another loop is called a nested loop. The depth of nested loop depends on the complexity of a problem. We can have any number of nested loops as required. Consider a nested loop where the outer loop runs n times and consists of another loop inside it. The inner loop runs m times. Then, the total number of times the inner loop runs during the program execution is n*m.
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.
In C++, vectors are used to store elements of similar data types. However, unlike arrays, the size of a vector can grow dynamically. That is, we can change the size of the vector during the execution of a program as per our requirements. Vectors are part of the C++ Standard Template Library. To use vectors, we need to include the vector header file in our program. The vector class provides various methods to perform different operations on vectors. Add Elements to a Vector: To add a single element into a vector, we use the push_back() function. It inserts an element into the end of the vector. Access Elements of a Vector: In C++, we use the index number to access the vector elements. Here, we use the at() function to access the element from the specified index.
The #ifndef directive of the C++ Programming Language helps in allowing the conditional compilation. The C++ Programming Language's preprocessor helps in determining only if the macro provided is not at all existed before including the specific subsequent code in the C++ compilation process. The #ifndef preprocessor only checks If the specific macro is not at all defined with the help of the #define directive. If the condition is TRUE then it will be helpful in executing the code otherwise the else code of the #ifndef will be compiled or executed only if present.
Return size. Returns the number of elements in the vector. This is the number of actual objects held in the vector, which is not necessarily equal to its storage capacity. vector::size() is a library function of "vector" header, it is used to get the size of a vector, it returns the total number of elements in the vector. The dynamic array can be created by using a vector in C++. One or more elements can be inserted into or removed from the vector at the run time that increases or decreases the size of the vector. The size or length of the vector can be counted using any loop or the built-in function named size(). This function does not accept any parameter.
A C++ template is a powerful feature added to C++. It allows you to define the generic classes and generic functions and thus provides support for generic programming. Generic programming is a technique where generic types are used as parameters in algorithms so that they can work for a variety of data types. We can define a template for a function. For example, if we have an add() function, we can create versions of the add function for adding the int, float or double type values. Where Ttype: It is a placeholder name for a data type used by the function. It is used within the function definition. It is only a placeholder that the compiler will automatically replace this placeholder with the actual data type. class: A class keyword is used to specify a generic type in a template declaration.
#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.
Break statement in C++ is a loop control statement defined using the break keyword. It is used to stop the current execution and proceed with the next one. When a compiler calls the break statement, it immediately stops the execution of the loop and transfers the control outside the loop and executes the other statements. In the case of a nested loop, break the statement stops the execution of the inner loop and proceeds with the outer loop. The statement itself says it breaks the loop. When the break statement is called in the program, it immediately terminates the loop and transfers the flow control to the statement mentioned outside the loop.
The pointer in C++ language is a variable, it is also known as locator or indicator that points to an address of a value. In C++, a pointer refers to a variable that holds the address of another variable. Like regular variables, pointers have a data type. For example, a pointer of type integer can hold the address of a variable of type integer. A pointer of character type can hold the address of a variable of character type. You should see a pointer as a symbolic representation of a memory address. With pointers, programs can simulate call-by-reference. They can also create and manipulate dynamic data structures. In C++, a pointer variable refers to a variable pointing to a specific address in a memory pointed by another variable.
Merge sorted ranges. Combines the elements in the sorted ranges [first1,last1) and [first2,last2), into a new range beginning at result with all its elements sorted. The C++ algorithm::merge function is used to merge elements of sorted ranges [first1, last1) and [first2, last2) to the range starting at result. In default version elements are compared using operator< and in custom version elements are compared using comp. The elements are compared using operator< for the first version, and comp for the second. The elements in both ranges shall already be ordered according to this same criterion (operator< or comp). The resulting range is also sorted according to this.
Exchange values of two objects. Exchanges the values of a and b. C++ Utility swap() function swaps or say interchanges the values of two containers under reference. The function std::swap() is a built-in function in the C++ Standard Template Library (STL) which swaps the value of two variables. This function does not return any value.
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.
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.
Column number of first matrix must be same as the row number of second matrix. Initialize matrix. Print values of the passed matrix and mutiply two matrices and return the resultant
This is a C++ Program to find "shortest path". Dijkstra's algorithm is very similar to Prim's algorithm for minimum spanning tree. Like "Prim's MST", we generate a SPT with given
"Change the Value" of the item stored in the pairing heap. Does nothing if newVal is larger than currently stored value. p points to node returned by insert. "newVal" is the new value