Coupon Accepted Successfully!


Bubble Sort Using Function Templates

In application software, large amounts of data are manipulated and sorting techniques are frequently used in such operations. The sorting mechanism helps view the information in different ways. The template function can also be used in the sorting operation. The following program illustrates the use of the template function with the bubble sorting method:
17.16 Write a program to sort integer and float array elements using bubble sort method.
template <class S>
void b_sort ( S u[], int k)
for (int x=0;x<k-1;x++)
for (int y=k-1;x<y;y--)
if (u[y]<u[y-1]) // checks successive numbers
S p;
p=u[y]; // assigns to temprary variable
u[y]=u[y-1]; // exchange of elements
u[y-1]=p; // collects from temporary variable
void main()
int i[5]={4,3,2,1,-4};
float f[5]={5.3,5.1,5.5,4.5,3.2};
b_sort(i,5); // call to function
b_sort(f,5); // call to function
int x=0,y=0;
cout<<“\nInteger array elements in ascending order:”;
while (x<5) cout<<i[x++] <<“ ”; // display contents of
// integer array
cout<<“\nFloat array elements in ascending order:”;
while ( y<5) cout<<f[y++] <<“ ”; // displays contents of
// float array
Integer array elements in ascending order: -4 1 2 3 4
Float array elements in ascending order : 3.2 4.5 5.1 5.3 5.5
Explanation: In the above program, b_sort() is a function with template and integer arguments. The two for loops are used to obtain two successive numbers of the array. The if statement checks the two successive numbers, and if the second number is greater than the first, they are exchanged using assignment statements. In the function main(), integer and float arrays are declared and initialized. The base addresses (of both arrays) of arrays and the number of elements are passed to the function b_sort(). The function b_sort() arranges the contents of both the arrays in ascending order. The two while loops display the contents of the arrays.

Test Your Skills Now!
Take a Quiz now
Reviewer Name