Wednesday 19 June 2013

source code: Bubble sort using C++ [easiest and user friendly]


#include <iostream>

using namespace std;


void bubbleSort(int *array,int length)
{
    int i,j;
    for(i=0; i<length; i++)
    {
        for(j=0; j<i; j++)
        {
            if(array[i]>array[j])
            {
                int temp=array[i];
                array[i]=array[j];
                array[j]=temp;
            }
        }
    }
cout<<"bubble sorted look of you array:";
for(i=0;i<length;i++)
        cout<<array[i]<<' ';
cout<<endl;
}

int main()

{
int length; int a[10];
cout<<"how long array you want:\nans: ";
cin>>length;
 
cout<<"\ninput the elements and hit ENTER afterwards:\nans: \n";

for(int x=0; x<length; x++)
cin>> a[x];

cout<<"the array you just entered:\n";

for(int x=0; x<length; x++)
cout<< a[x]<<' ';
cout<<endl;



    bubbleSort(a, length);

}

2 comments:

  1. It will be little bit faster if you use a flag. Btw nice work.

    ReplyDelete
    Replies
    1. hm okay i'll check. n of course thanks for the suggestion.

      Delete