Brief introduction
The bubble algorithm is a basic sort algorithm that repeats the comparison of the two adjacent elements in the array. If one element is larger (smaller) than the other, then the position of the two elements is exchanged. Repeat this comparison until the last element. This comparison will repeat the n-1, each trip to compare N-j times, J is already sorted the number of elements. Each comparison is able to find the largest or smallest number in the unsorted element. It's like a blister floating from the bottom to the surface. Bubble sort is a kind of scheduling method with high time complexity and low efficiency. The spatial complexity of the is O (n).
1, Worst time complexity O (n^2)
2, Average time complexity O (n^2)
Realize the idea
1, each comparison compares the size of two adjacent elements in the array
2, if I element is less than the i-1 element, swap the position of two elements
3, repeat n-1 trip comparison
objective-c Example:
+ (void) bubbleSort: (NSMutableArray *) list {
if (list.count <= 1) {
return;
}
int i, y;
BOOL bFinish = YES; // Whether data exchange occurs
for (i = 1; i <= [list count] && bFinish; i ++) {
bFinish = NO; // Every traversal, reset the flag
// Start from the last digit and compare it with the previous digit one by one. If it is smaller, exchange positions
// When there is no data exchange in a traversal, it means that the sorting has been completed (bFinish = YES), then no loop will be performed.
for (y = (int) [list count] -1; y> = i; y--) {
if ([[list objectAtIndex: y] intValue] <[[list objectAtIndex: y-1] intValue]) {
// Swap position
// NSLog (@ "% d <->% d", [[array objectAtIndex: y-1] intValue], [[array objectAtIndex: y] intValue]);
[list exchangeObjectAtIndex: y-1 withObjectAtIndex: y];
bFinish = YES; // Data exchange occurs, continue to the next traversal, until no data exchange occurs or the cycle is completed
// NSLog (@ "% @", [array componentsJoinedByString: @ ""]);
}
}
}
} }
}
}