Sorting a given list ascendingly using an array type C++ code example
Compiler: Visual C++ Express Edition 2005
Compiled on Platform: Windows XP Pro SP2
Header file: Standard
Additional project setting: Set project to be compiled as C++
Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C++ Code (/TP)
Other info: none
To do: Sorting a given list ascendingly using an array type in C++ programming
To show: How to sort a list ascendingly using array type in C++ programming
// a simple sorting program that sort a list of n integer numbers, entered by the user (ascending)
#include <iostream>
using namespace std;
#define maxsize 100
int main(void)
{
int temp, i, j, n, list[maxsize];
cout<<"\n--You are prompted to enter your list size.--";
cout<<"\n--Then, for your list size, you are prompted to enter--";
cout<<"\n--the element (integers) of your list.--";
cout<<"\n--Finally your list will be sorted ascending!!!--\n";
// enter the list's size
cout<<"\nEnter your list size: ";
// read the list's size
cin>>n;
// prompting the data from user store in the list
for(i=0; i<n; i++)
{
cout<<"Enter list's element #"<<i<<"-->";
cin>>list[i];
}
// do the sorting...
for(i=0; i<n-1; i++)
for(j=i+1; j<n; j++)
if(list[i] > list[j])
{
// These three lines swap the elements
// list[i] and list[j].
temp = list[i];
list[i] = list[j];
list[j] = temp;
}
cout<<"\nSorted list, ascending: ";
for(i=0; i<n; i++)
cout<<" "<<list[i];
cout<<endl;
return 0;
}
Output example:
--You are prompted to enter your list size.--
--Then, for your list size, you are prompted to enter--
--the element (integers) of your list.--
--Finally your list will be sorted ascending!!!--
Enter your list size: 5
Enter list's element #0-->23
Enter list's element #1-->20
Enter list's element #2-->45
Enter list's element #3-->67
Enter list's element #4-->10
Sorted list, ascending: 10 20 23 45 67
Press any key to continue . . .