my code stock.com

This program takes input for a 1D array and then uses Selection & Bubble sorting techniques to sort the elements of the array.

Snippet options

Download: Download snippet as 1d-array-sorting.cpp.
Copy snippet: For this you need a free my code stock.com account.
Embed code : You will find the embed code for this snippet at the end of the page, if you want to embed it into a website or a blog!

#include <iostream>
#include<stdlib.h>
using namespace std;
int main()
{
    system("cls");
    cout << "\t\t Sorting An Array\n" << endl;
    cout<<"Enter the Number of Elements in the Array : ";
    int i,j,n,Min,Pos,ch,temp;
    cin>>n;
    int* Arr1D = new int[n];
    for (i=0; i<n; i++)
    {
        cout<<"Enter the "<<i+1<<"st Element : ";
        cin>>Arr1D[i];
    }
    cout<<"\nArray before Sorting:\n";
    for (i=0; i<n; i++)
    {
        cout<<Arr1D[i]<<"\t";
    }
    cout<<"\n\nChoose Sorting Technique:\n";
    cout<<"\t1. Selection Sort.\n";
    cout<<"\t2. Bubble Sort.\n\n";
    cout<<"Your Choice : ";
    cin>>ch;
    switch (ch)
    {
        case 1 : for (i=0; i<(n-1); i++)
                 {
                     Min = Arr1D[i];
                     Pos = i;
                     for (j=i+1; j<n; j++)
                     {
                         if (Arr1D[j] < Min)
                         {
                             Min = Arr1D[j];
                             Pos = j;
                         }
                     }
                     Arr1D[Pos] = Arr1D[i];
                     Arr1D[i] = Min;
                 }
                 break;
        case 2 : for(i=0; i<n; i++)
                 {
                     for(i=0; i<(n-1); i++)
                     {
                         for(j=0; j<(n-i-1); j++)
                         {
                             if( Arr1D[j] > Arr1D[j+1] )
                             {
                                 temp = Arr1D[j];
                                 Arr1D[j] = Arr1D[j+1];
                                 Arr1D[j+1] = temp;
                             }
                         }
                     }
                 }
                 break;
    }
    cout<<"\nArray after Sorting:\n";
    for (i=0; i<n; i++)
    {
        cout<<Arr1D[i]<<"\t";
    }
    delete [] Arr1D;
    Arr1D = NULL;
    cout<<endl;
    return 0;
}

Create a free my code stock.com account now.

my code stok.com is a free service, which allows you to save and manage code snippes of any kind and programming language. We provide many advantages for your daily work with code-snippets, also for your teamwork. Give it a try!

Find out more and register now

You can customize the height of iFrame-Codes as needed! You can find more infos in our API Reference for iframe Embeds.