Home »
C++ Programs
C++ program to sort an array in ascending order using class
Submitted by Shubh Pachori, on August 13, 2022
Problem statement
Given an array, we have to sort it in ascending order using the class and object approach.
Example:
Input:
array[0]: 22
array[1]: 1
array[2]: 44
array[3]: 5
array[4]: 33
Output:
Sorted Array is 1 5 22 33 44
C++ code to sort an array in ascending order using class and object approach
#include <iostream>
using namespace std;
// create a class
class Array {
// private data member
private:
int array[5];
// public functions
public:
// getArray() function to get the value of the array
void getArray() {
for (int index = 0; index <= 4; index++) {
cout << "array[" << index << "]:";
cin >> array[index];
}
}
// putArray() function to print the array
void putArray() {
for (int index = 0; index <= 4; index++) {
cout << array[index] << " ";
}
}
// sortAscending() function to sort the array in ascending order
void sortAscending() {
// initialising int type variables to perform operations
int index_1, index_2, temp;
// for loop to read the whole array
for (index_1 = 0; index_1 <= 4; index_1++) {
// for loop to compare numbers of array
for (index_2 = 0; index_2 < 4 - index_1; index_2++) {
// if condition to check if the next term is smaller than
// this then swapping takes place
if (array[index_2] > array[index_2 + 1]) {
// swapping numbers if numbers
// are not in the order
temp = array[index_2];
array[index_2] = array[index_2 + 1];
array[index_2 + 1] = temp;
}
}
}
}
};
int main() {
// create a object
Array A;
// function is called by the object to store the array
A.getArray();
// sortAscending() function is called by the object to find the
// sort the array in ascending order
A.sortAscending();
cout << "Sorted Array is ";
// putArray() function is called to print the array
A.putArray();
return 0;
}
Output
array[0]: 44
array[1]: 66
array[2]: 5
array[3]: 444
array[4]: 33
Sorted Array is 5 33 44 66 444
Explanation
In the above code, we have created a class Array, one int type array data member array[5] to store the values, and public member functions getArray(), putArray(), and sortAscending() to store the given values in array, to print the whole array and to sort the array in ascending order.
In the main() function, we are creating an object A of class Array, reading integer values by the user of the array using the getArray() function, and finally calling the sortAscending() member function to sort the given array. The sortAscending() function contains the logic to sort the given array in ascending order and printing the result using putArray() function.
C++ Class and Object Programs (Set 2) »