0

I want to sort array using Bubble Sort. I an missing a small point due to which array is not sorted properly. I would highly appreciate if somebody can figure out the issue.

int i,k;    
int flag = 1;   
MReview *store1 ,*store2,*tempSwap;  
tempSwap = [[MReview alloc] init];  
store1 = [[MReview alloc] init];  
store2 = [[MReview alloc] init];  

for (i = 1;i <= ([arrSortWeeks count]) && flag; i++)
{  
    NSLog(@"Next Iteration: %d", i+1);  
    flag = 0;  
    for (k = 0;   k < ([arrSortWeeks count]-1);   k++)
    {

      store1 = [arrSortWeeks objectAtIndex:k+1];   
      store2 = [arrSortWeeks objectAtIndex:k];  
      //Confronto returns -1 if Store1 is greater and returns 1 if Store1 is smaller
      if (([self confronto:store1.ReviewDate :store2.ReviewDate]) == -1) 
      {    
         tempSwap = store2;  
         store2 = store1;  
         store1 = tempSwap;  
         //[store1 retain];  
         //[store2 retain];  

         [arrSortWeeks replaceObjectAtIndex:k+1 withObject:store1];  
         [arrSortWeeks replaceObjectAtIndex:k withObject:store2];

         flag = 1;  
       }
    }
}
Taimur Ajmal
  • 2,778
  • 6
  • 39
  • 57

3 Answers3

3

If this is for an academic exercise (why else would you use Bubble sort?) then please refer to other posters' responses.

If this is for code to be used in the real world, be aware that Bubble Sort is a very slow sorting method, and not generally recommended for anything beyond a learning tool.

Big O notation is one means of describing the time complexity of sorting algorithms. Bubble Sort's time complexity is O(n2), which means that the time will be a function of the square of the number of elements being sorted, i.e. extremely slow for more than a few elements.

In general, you should be using built-in sort methods wherever possible, as these will have been optimised to sort much more quickly.

This post describes the built-in methods for sorting in iOS, which have the added benefit of being far more concise and readable, as well as being much faster than Bubble Sort.

Community
  • 1
  • 1
jnic
  • 8,695
  • 3
  • 33
  • 47
2

You are iterating your array only ones. BubbleSort needs n^2 iterations to sort your array.

for(int i=0; i< [array count]-2; i++) {
for(int j=1; j< [array count]-1; j++) {
    if([array objectAtIndex:i] > [array objectAtIndex:j]) {
        // SWAP THEM
    }
}
}

The posted code does not exactly fit to what you are doing by i guess you can see what I mean.

Max
  • 989
  • 8
  • 11
0

Instead of removing and adding the objects at particular index, just use the method to replace.

Ex: [arrSortWeeks replaceObjectAtIndex:k+1 withObject:store2];

Also this post will help you how to sort NSMutableArray with custom objects.

Community
  • 1
  • 1
KingofBliss
  • 15,055
  • 6
  • 50
  • 72