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;
}
}
}
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.