Write a C++ program using the concept of OOP to sort elements of array in ascending order


 Here is an example of an algorithm and C++ program that uses the concept of object-oriented programming to sort the elements of an array in ascending order:

Algorithm:

  1. Create a class called "Array"
  2. Define variables for size and a pointer to an array to store the elements
  3. Create a constructor to initialize the size and allocate memory for the array
  4. Create a method called "input" to take input from the user and store it in the array
  5. Create a method called "sortAscending" to sort the elements of the array in ascending order using bubble sort
  6. Create a method called "display" to display the elements of the array
  7. Create an object of the Array class and use the methods to sort the elements of the array and display the result

C++ Program:

#include <iostream>
using namespace std;
 
class Array {
    int size;
    int *arr;
  public:
    Array(int s) {
        size = s;
        arr = new int[size];
    }
    void input() {
        cout << "Enter elements of array: " << endl;
        for(int i = 0; i < size; i++)
            cin >> arr[i];
    }
    void sortAscending() {
        for(int i = 0; i < size; i++) {
            for(int j = 0; j < size-i-1; j++) {
                if(arr[j] > arr[j+1]) {
                    int temp = arr[j];
                    arr[j] = arr[j+1];
                    arr[j+1] = temp;
                }
            }
        }
    }
    void display() {
        cout << "Sorted array in ascending order: ";
        for(int i = 0; i < size; i++)
            cout << arr[i] << " ";
        cout << endl;
    }
    ~Array() {
        delete[] arr;
    }
};
 
int main() {
    int s;
    cout << "Enter the size of the array: ";
    cin >> s;
    Array a(s);
    a.input();
    a.sortAscending();
    a.display();
    return 0;
}
 
 
/*
======Input/Output=====
 
Enter the size of the array: 5
Enter elements of array: 
5 3 2 8 1
 
 
Sorted array in ascending order: 1 2 3 5 8
*/


Explanation:

  • The user enters 5 for the size of the array, indicating that the array has 5 elements.
  • The user then enters the elements of the array: 5 3 2 8 1
  • The program creates an Array object, sorts the array in ascending order using bubble sort, and displays the result: 1 2 3 5 8
#OOP
#HappyProgramming
#HappyCoding

No comments:

Post a Comment