Sorting the array.

I need to write array and sort array elements from low to hight number.

This is what I have done, but dont have a clue how sort numbers by growing numbers..

This is what I have done... I am using dev C++
[code]

[#include <iostream>

using namespace std;

int main()
{

int n;
cout << "enter size of array" << endl;
cin >> n;
int b[n];
cout << "enter number elements:"<< endl;
for(int i = 0; i < n;i++)
{
cin >> b[i];
}
cout << endl << endl; //SO WHATS NEXT ? HOW TO SORT THEM ?










system("PAUSE");


return 0;
}

]
Last edited on
closed account (2LzbRXSz)
hopkins123 wrote:
growing numbers

Ascending order, right?

You could do that with the sort function
http://www.cplusplus.com/reference/algorithm/sort/

Since you're using an array, you'd have to write it like
sort(b, b+n);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include<iostream>
using namespace std;

void sort (int n);
void swap (int *p1 , int *p2);

int a[10];

int main()
{
	int i;
	for (i=0;i<10;i++)
	{
		cout<<"Enter array element #"<<i<<":";
		cin>>a[i];
		
	}
	sort(10);
	
	cout<<"Here is your array sorted :"<<endl;
	for (i=0;i<10;i++)
		cout<<a[i]<<" ";
	
	cin.get();
        cin.ignore();
	return 0;
	
}

void sort(int n)
{
	int i,j,high;
	for (i=0;i<n-1;i++)
	{
		high=i;
		for (j=i+1;j<n;j++)
			if(a[j]>a[high])
				high=j;
			
			if (i!=high)
				swap(&a[i], &a[high]);
			
	}
}

void swap(int *p1,int *p2)
{
	int temp =*p1;
	*p1=*p2;
	*p2=temp;
}









Probably the simplest it can get.
Last edited on
Topic archived. No new replies allowed.