Tuesday, 22 January 2013

Bubble Sort

I won’t go as far as explaining how the bubble sort technique works but will show with a block of code. You can actually copy the code and run it on your compiler. Everything has been done for you. Again, the commenting on the code is there to help you understand what’s really going on when bubble sorting.

This is a C++ program that applies the bubble sort technique. It sorts ten elements of an array into ascending order.

//Bubble Sort


using namespace std;

int main()
    int arr[]={8,7,5,4,2,1,0,3,6,9};
    int temp; //temporary storage
    for(int j=0; j<9; j++) //helps the second loop by controlling number of passes
    for(int i=0; i<10; i++) //runs through the array and compares the values, the larger goes down
        if (arr[i]>arr[i+1]) //compares the first array index value with the second array index value
          temp=arr[i]; //send the first array index value to temporary storage
          arr[i]=arr[i+1]; //send the second value to the place of the first value, index wise

          arr[i+1]=temp; //take temp which is the first value to the second array index or position
             //this only happens when the first value is greater that the second
    }   for(int i=0; i<10;i++) //for printing the array elements
          return 0;

Observe: The comments should have the "//" before them. You'll actually see that mine have continued to the next line without them. You go ahead and fix that!

There are many ways to do it. My intention was to give beginners some insight into this array sorting technique.  

No comments:

Post a Comment