What am I doing wrong with this sort?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Ellipsis
    New Member
    • Jul 2008
    • 5

    What am I doing wrong with this sort?

    I am trying to sort an array of numbers from greatest to least using a bubblesort thingy but it wont work for me heres the code I have...
    Code:
    #include <iostream>
    using namespace std;
    class sort
    {
    public:
    	void BubbleSort (int arr[], int length)
    	{
    		bool swap= true;
    		int temp;
    		for (int i = 0; swap; i++)
    		{
    			if(arr[i] > arr[i + 1])
    			{
    				temp = arr[i];
    				arr[i] = arr [i + 1];
    				arr [i+1] = temp;
    				swap = true;
    			}
    		}
    	}
    };
    int main()
    {
    	sort* mySort = new sort;
    	int a[] = {4, 14, 5, 0, 3, 23, 7, 16, 26, 34, 45, 54, 1, 9, 6, 15, 20, 8, 32, 86};
    	(*mySort).BubbleSort ((a),(sizeof(a)/4));
    	for (int i = 0; i < (sizeof (a) / 4); i++)
    	{
    		cout << a[i] << ", ";
    	}
    	cout << "\n";
    	return 0;
    }
    I am probably making a stupid mistake so dont laugh :P
  • phiefer3
    New Member
    • Jun 2007
    • 67

    #2
    For one thing, your swap variable is always true, it's initialized to true, and nothing in your code ever makes it false, so the way you use it as a loop control variable means that you're going to get an infinite loop.

    Also, even though you pass the length of the array to the sort function you never actually use it. length should be the loop control variable, the swap variable isn't necessary.

    Finally, a bubble sort requires a nested pair of loops, in other words a loop inside a loop. It should look something like this:

    [CODE=C++]
    void BubbleSort(int arr[], int length)
    {
    for(int i = 0; i < length; i++)
    {
    for(int j = i; j < length; j++)
    {
    if(arr[j] > arr[i])
    {
    int temp = arr[i];
    arr[i] = arr[j];
    arr[j] = temp;
    }
    }
    }
    }
    [/CODE]

    The outer loop keeps track of how much of the list is sorted (in other words i is the index of the first unsorted element). The inner loop passes over the unsorted part of the list looking for the largest element in the unsorted part of the list and swaps it to the front of the unsorted portion. Once the inner loop finishes, the first element of the unsorted portion is now sorted and the outer loop moves ahead to the next unsorted element and repeats the process.

    Comment

    • Ellipsis
      New Member
      • Jul 2008
      • 5

      #3
      Thank you very much...

      Comment

      Working...