Develop a program that will sort the elements of a single dimension array. Program Requirements:
1. Declare a single dimension array of size n
2. Input n elements to a single dimension array
3. Sort the elements of an array from highest to lowest and vice versa
Also, the program will identify and output the highest and lowest integer.
I have used c++ language as the language is not specified in the question.
Code :
#include <iostream>
using namespace std;
//fucntion to sort the array in high to low order
int *high_to_low(int arr[],int n)
{
for(int i = 0;i<n;i++)
{
for(int j = i;j<n;j++)
{
if(arr[i]<arr[j])
{
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
return arr; //return the base address of the array i.e zero index
address;
}
//function to sort the array in low to high order
int *low_to_high(int arr[],int n)
{
for(int i = 0;i<n;i++)
{
for(int j = i;j<n;j++)
{
if(arr[i]>arr[j])
{
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
return arr; //return the base address of the array i.e 0th
index;
}
int main()
{
int n;
cout<<"Enter the size of array : ";
cin>>n; //taking input of n
int arr[n];
for(int i = 0;i<n;i++)
{
cin>>arr[i]; //taking input of n elements for array
}
cout<<"Array from high to low order :"<<endl;
int *p = high_to_low(arr,n); //calling sort array function
high_to_low
for(int i = 0;i<n;i++)
{
cout<<*(p+i)<<" "; //printing using pointer + the index
i.e i
}
cout<<endl;
cout<<"Array from low to high order :"<<endl;
int *q = low_to_high(arr,n); //calling sort array function
low_to_high
for(int i = 0;i<n;i++)
{
cout<<*(q+i)<<" "; //printing using pointer + the index
i.e i
}
int max = *(q+n-1); //in low_to_high max will be n-1 because index
start from 0
int min = *(q); //in low_to_high min will be 0th index
element
cout<<endl;
cout<<"Max element in the array :
"<<max<<endl;
cout<<"Min element in the array :
"<<min<<endl;
return 0;
}
Output :
Execution :
Please feel free to ask any query in the comment section.
Get Answers For Free
Most questions answered within 1 hours.