After many hours can't figure out why the sorting and searching is not working... When running tests it I always get "Didn't find needle in haystack" whether the value is in or not in the array...

Here is a piece of my code that does the sorting. Please help!

Buble sort


First, what is shown won't compile. didSwap; will generate an error. So let's assume that it is really didSwap++; Now, the sort will usually fail as written. If you have a list where an element is less than the remaining elements, but the remaining elements are not sorted, it will fail. Try testing the following list: 2, 1, 3, 5, 4 It will sort out to 1, 2, 3, 5, 4. As soon as the first element is found to be in the correct location, the break will execute and stop the sort. You actually have to sort through the whole list. To verify your code, add a for loop after the sort to print out your list to see what it produces. Something like this (you can remove it once the code works):

    for( int i = 0; i < n; i++ )
        printf("sorted: values[%i] =%i.\n", i, values[i]);

As for the not found, if you are using a binary search, it may or may not fail with a partially sorted list, depending on the search value (the needle) and the list (the haystack). Fixing the sort may fix the search or it may not. If it doesn't, I suggest sumbmitting that as a new question.

If this answers your question, please accept this answer to remove your question from the unanswered question pool. Let's keep up on forum maintenance. ;-)

  • Thanks for your help Cliff B. I spent several hours trying to fix this but could not figure it out with Bubble sort. I simply used another sorting algorithm and "voila" it worked! Sorry for the late comment but i am now working on Pset4 – Robert R. Jul 3 '15 at 20:06

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .