• September 22, 2021

PHSARIT

Bring Technology Ideas with you

 C++ programming to sort array element

As the previous post, we have demonstrated the way how we can find the largest and smallest in array elements. This tutorial will enhance how you can sort those array elements in to order from smallest to largest and from largest to smallest.

The programming of C++ to sort array from smallest to largest:

// by asensding order. From smallest to largest
	int valueTemp;
	for (int i = 0; i < n ; ++i)
	{
		for (int j = i + 1; j < n; ++j) //compare value again and again
		{
			if (arr[i] > arr[j]) //if it is true, through value to temp value
			{
				valueTemp = arr[i]; //store value tempory
				arr[i] = arr[j]; //compare i and j, if equal
				arr[j] = valueTemp; // set J=store value temport
			}
		}
	}
	cout << "Sorting Order Array:";
	for (int i = 0; i < n; ++i)
		cout << arr[i] << endl;

The programming of C++ to sort array from largest to smallest:

// sort descending from Largest to smallest
	for (int i = 0; i < n; ++i)
	{
		for (int j = i + 1; j < n; ++j) //compare value again and again
		{
			if (arr[i] < arr[j]) // if it is true through value to temp 
			{
				valueTemp = arr[i]; //store value tempory in array i
				arr[i] = arr[j]; //compare i and j, if equal
				arr[j] = valueTemp; // set J=store value temport
			}
		}
	}
	cout << "Sorting Descending Array:";
	for (int i = 0; i < n; ++i)
		cout << arr[i] << endl;

The full code of the project to sort array as below:

#include<iostream>
using namespace std;
int main()
{
	//set user to input the number of the array in the limitation
	int n;
	cout << "Enter amount of no more than 100 elements to store:";
	cin >> n;
	int arr[100];
	// all users to enter the elements
	for (int i = 0; i < n; i++)
	{
		cout << "Element:" << i + 1 << ":" << endl;
		cin >> arr[i];
	}
	// print all elements
	cout << endl;
	cout << "You have enter all element:";
	for(int i=0;i<n;i++){
		cout << arr[i];
	}
	cout << endl;
int valueTemp;
	for (int i = 0; i < n ; ++i)
	{
		for (int j = i + 1; j < n; ++j) //compare value again and again
		{
			if (arr[i] > arr[j]) //if it is true, through value to temp value
			{
				valueTemp = arr[i]; //store value tempory
				arr[i] = arr[j]; //compare i and j, if equal
				arr[j] = valueTemp; // set J=store value temport
			}
		}
	}
	cout << "Sorting Order Array:";
	for (int i = 0; i < n; ++i)
		cout << arr[i] << endl;
	// sort descending from Largest to smallest
	for (int i = 0; i < n; ++i)
	{
		for (int j = i + 1; j < n; ++j) //compare value again and again
		{
			if (arr[i] < arr[j]) // if it is true through value to temp 
			{
				valueTemp = arr[i]; //store value tempory in array i
				arr[i] = arr[j]; //compare i and j, if equal
				arr[j] = valueTemp; // set J=store value temport
			}
		}
	}
	cout << "Sorting Descending Array:";
	for (int i = 0; i < n; ++i)
		cout << arr[i] << endl;
system("pause > 0");
}

See the result

    result from compiling

    Related post