# Simple example of ES0en ES1en implementing bubble sort algorithm

• 2020-06-07 05:20:57
• OfStack

Introduction to the
The bubble algorithm is a basic sorting algorithm that repeatedly compares two adjacent elements of an array. If one element is larger (smaller) than the other, then the two elements are swapped. Repeat the 1 comparison until the last element. This 1 comparison repeats ES2en-1, each time comparing ES3en-ES4en, which is the number of elements already sorted. At each step of the comparison, you find the largest or smallest number in the unsorted element. This is like bubbles floating from the bottom to the surface one by one. Bubble sort is a kind of sorting method with high time complexity and low efficiency. Its space complexity is O(n).
1, worst time complexity O(n^2)
2, average time complexity O(n^2)

Implementation approach
1. Compare the size of two adjacent elements in the array every 1 round
2. If the i element is less than the i-1 element, switch the two elements
3. Repeat the comparison of n-1

Objective - C example:

``````
+(void)bubbleSort:(NSMutableArray *)list{
if (list.count <= 1) {
return;
}
int i, y;
BOOL bFinish = YES; // Whether data exchange has occurred
for (i = 1; i<= [list count] && bFinish; i++) {
bFinish = NO; // Reset the flag for each pass
// From the last 1 Start with bits and go in order 1 If the bits are smaller, swap them
// when 1 If there is no data exchange for the second traversal, the sorting is complete (bFinish=YES) , the loop will not be repeated
for (y = (int)[list count]-1; y>=i; y--) {
if ([[list objectAtIndex:y] intValue] < [[list objectAtIndex:y-1] intValue]) {
// Swap places
//    NSLog(@"%d<->%d",[[array objectAtIndex:y-1] intValue],[[array objectAtIndex:y] intValue]);
[list exchangeObjectAtIndex:y-1 withObjectAtIndex:y];
bFinish = YES; // If data exchange occurs, proceed 1 Iterate until no data exchange occurs or the loop completes

//    NSLog(@"%@",[array componentsJoinedByString:@" "]);
}

}
}
}

``````

Related articles: