Write a C/C++ program that prompts the user to enter N integer values and stores it in an array. Sort the elements of the array in ascending order. You may use any sorting algorithm.
Write a C/C++
A required program in C++ language is as follows,
#include<iostream>
using namespace std;
void swap(int *a, int *b)
{
int tempV = *a;
*a = *b;
*b = tempV;
}
//Define a function to sort the array elements in ascending order
void sortAsc(int arry[], int N)
{
//Declare necessary variables
int ind, jind, min;
for (ind = 0; ind < N-1; ind++)
{
// Discover the minimum element in unsorted array
min = ind;
for (jind = ind+1; jind < N; jind++)
if (arry[jind] < arry[min])
min = jind;
/* Call the method to swap the minimum element
found with the first element*/
swap(&arry[min], &arry[ind]);
}
}
// Define main() function
int main()
{
int N,ind;
cout<<"How many elements should be sorted in the array?\t";
//Get the number of elements to be stored in an array
cin>>N;
int arry[N];
for(ind=0;ind<N;ind++)
{
cout<<"Enter value for element at index "<<ind<<":\t";
//Get the values from the user
cin>>arry[ind];
}
sortAsc(arry, N);
cout << "Sorted array: ";
//Print the sorted array
for (ind=0; ind < N; ind++)
cout << arry[ind] << " ";
return 0;
}
Step by step
Solved in 3 steps with 3 images