Menu

Bubble Sort?

Anonymous
2002-11-30
2012-09-26
  • Anonymous

    Anonymous - 2002-11-30

    This does not appear to sort random numbers.
    // The Bubble Sort!

    #include<iostream>
    #include<cstdlib>

    using namespace std;

    int main()      {

    int nums[10];
    int a, b, t;
    int size;

    size = 10;//number of elements to sort.

    //give array some random initial values
    for(t=0; t<size; t++) nums[t] = rand();
    //display original array
    cout<<"Original array is: ";
    for(t=0; t<size; t++) cout<< nums[t] << ' ' ;
    cout<<'\n';

    //this is the bubble sort
    for(a=1; a<size; a++)
    for(b=size-1; b>=a; b--)   {

    if(nums[b-1] > nums[b])  { //if out of order

    //exchange elements
    t = nums[b-1];
    nums[b-1] = nums[b];
    nums[b]=t;

            }
           
            }
            //this is the end of the bubble sort
           
            //display sorted array
            cout<<"Sorted Array is:"  ;
           
            for( t=0; t= size; t++)  cout << nums[t] <<' ' ;
           
          int get();
           
            return 0;
           
            }

     
    • Nobody/Anonymous

      This line has an error in your logic, can you see it.  Hint, it involves the middle of the for statement:

      for( t=0; t= size; t++) cout << nums[t] <<' ' ;

      You typo'ed into an infinite loop, it should read:

      for( t=0; t< size; t++) cout << nums[t] <<' ' ;

      It seems to work fine once this is fixed.  I put a pause in to my version:

      #include<iostream>
      #include<cstdlib>
      #include<stdlib.h>

      using namespace std;

      int main() {

      int nums[10];
      int a, b, t;
      int size;

      size = 10;//number of elements to sort.

      //give array some random initial values
      for(t=0; t<size; t++) nums[t] = rand();
      //display original array
      cout<<"Original array is: ";
      for(t=0; t<size; t++) cout<< nums[t] << ' ' ;
      cout<<'\n';

      //this is the bubble sort
      for(a=1; a<size; a++)
      for(b=size-1; b>=a; b--) {

      if(nums[b-1] > nums[b]) { //if out of order

      //exchange elements
      t = nums[b-1];
      nums[b-1] = nums[b];
      nums[b]=t;

      }

      }
      //this is the end of the bubble sort

      //display sorted array
      cout<<"Sorted Array is:" ;

      for( t=0; t< size; t++) cout << nums[t] <<' ' ;

      int get();
      system("pause");
      return 0;

      }

      Wayne

       

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.