C:
函数声明写在.h里:
void bubble(int array[],int count);
函数定义写在.m里,算法用到了临时变量来交换两个数:
void bubbleSort(int *array,int count )
{
for (int i =0; i < count - 1; i++) {
for (int j =0; (j = count - 1 - i); j++) {
if (array[j] > array[j + 1]) {
int temp = array[j];
array[j] = array[j +1];
array[j +1] = temp;
}
}
}
}
int main(int argc,const char * argv[])
{
int array[10] = {0};
for (int i =0; i < 10;i++) {
array[i] =arc4random() % 100 +10;
}
bubbleSort(array,10);
for (int i =0; i < 10; i++) {
printf("%d ", array[i]);
}
return 0;
}
NSMutableArray * array = [NSMutableArray arrayWithArray:@[@"2", @"1", @"3", @"0", @"5", @"4"]];
NSString * temp;
for (int i = 0; i < [array count] - 1; i++) {
for (int j = 0; j < [array count] - 1 - i; j++) {
if ([[array objectAtIndex:j]integerValue] > [[array objectAtIndex:j + 1]integerValue]) {
temp = [array objectAtIndex:j];
[array replaceObjectAtIndex:j withObject:[array objectAtIndex:j + 1]];
[array replaceObjectAtIndex:j + 1 withObject:temp];
}
}
}
NSLog(@"Bubbles are %@", array);