# Sorting

• 03-14-2005
hopeolicious
Sorting
can show me how can i get my program to sort an array of elements that are user input and output them

Code:

```#include <iostream> using namespace std; const int LIMIT = 50; int main() {     int MYARRAY[LIMIT];     int value;     int i = 0;     int print = 0;     bool exit = false;         while(!exit && i < LIMIT)     {         cout<<"Enter a number or 999 to quit ";         cin>>value;                         if(value != 999)         {             MYARRAY[i] = value;             i++;         }         else         {             exit = true;//if value equals 999 exit the loop         }             }            while(print < i)     {         cout<<MYARRAY[print]<<endl;//print out the number as long as it is less than i         print++;     }     //"pause" the program     cin.ignore(80,'\n');     cin.get();     return 0; }```
• 03-15-2005
scoobasean

An easy one is Bubble Sort:

http://www.cs.princeton.edu/~ah/alg_...ubbleSort.html
• 03-15-2005
treenef
If you look on the web you will find a whole host of different sorting algorithms, some more complicated than others.

If you plan to make one by yourself you will eventually realise the easiest sorting algo requires a 'nested for loop'. This is the sorting algorithm outlined in 'bubble sort' I think. Its easy to understand however, some algorithms are extremely difficult to understand such as the 'quick sort' algorithm.

You can find this algorithm on the net but I have written the code here for you. All you have to do is copy and paste into your programme. The quick sort is especially useful because of all the algo's its the fastest to sort elements into ascending order:

Code:

```#include <stdio.h> #include <iostream.h> int quickSort(int numbers[],int); int q_sort(int numbers[],int,int); int main() { int array[81]; for (int a=0; a<10; a++) { cout<<"Enter an integer value:"; cin>>array[a]; } // call the function quickSort(array,10); //print values for (int b=0; b<10; b++) { cout<<array[b]<<endl; } int stop; cin>>stop; } int quickSort(int numbers[], int array_size) {   q_sort(numbers, 0, array_size - 1); } int q_sort(int numbers[], int left, int right) {   int pivot, l_hold, r_hold;   l_hold = left;   r_hold = right;   pivot = numbers[left];   while (left < right)   {     while ((numbers[right] >= pivot) && (left < right))       right--;     if (left != right)     {       numbers[left] = numbers[right];       left++;     }     while ((numbers[left] <= pivot) && (left < right))       left++;     if (left != right)     {       numbers[right] = numbers[left];       right--;     }   }   numbers[left] = pivot;   pivot = left;   left = l_hold;   right = r_hold;   if (left < pivot)     q_sort(numbers, left, pivot-1);   if (right > pivot)     q_sort(numbers, pivot+1, right); }```
• 03-15-2005
Togra
Is this ment as an exercise? If not: just use std::sort from <algorithm> :).