Write a C++ program to create dynamic integer array, and sort them in ascending order, using new and delete operators.
Aug 15, 2018The following program is tested with gcc version 7.3.0 (Ubuntu 7.3.0-16ubuntu3).
// program to allocate memory for the //one dimentional array and sort them in ascending order // using c++ new and delete operators #include<iostream> using namespace std; int main(){ int *arr_pointer; //pointer variable for holding the array address int NUMBER; cout<<"Enter Number of terms:"<<endl; cin>>NUMBER; arr_pointer = new int[NUMBER]; //allocating memory for Total array elements cout<<"Enter the elements of array:"<<endl; for (int i = 0; i < NUMBER; i++) { cin>>*(arr_pointer + i); //using pointer notation } //looping that sorts the array elements in ascending order for (int i = 0; i < NUMBER; i++) { for (int j = i + 1; j < NUMBER; j++) { if (*(arr_pointer + i) > *(arr_pointer + j)) { int temp; temp = *(arr_pointer + i); *(arr_pointer + i) = *(arr_pointer + j); *(arr_pointer + j) = temp; } } } cout<<"Sorted array is :"<<endl; for (int i = 0; i < NUMBER; i++) { cout<<*(arr_pointer + i)<<", "; } cout<<endl; //de-allocating the memory allocated delete [] arr_pointer; return 0; }
SAMPLE RUN :
Enter Number of terms: 12 Enter the elements of array: 2 4 6 3 2 1 8 9 50 34 56 66 Sorted array is : 1, 2, 2, 3, 4, 6, 8, 9, 34, 50, 56, 66,