iOS获取元素的交集 并集 选择排序 冒泡排序 插入排序

NSArray *array1=@[@"1",@"4",@"5",@"6",@"8",@"9"];

NSArray *array2=@[@"2",@"3",@"5",@"6",@"7",@"5"];

NSMutableArray *array=[[NSMutableArray alloc]init];

//交集 还是不能相同元素

for (int i=0;i<array1.count;i++){

for (int j=0; j<array2.count;j++){

if (array1[i]==array2[j]) {

if (![array containsObject:array1[i]]) {

[array addObject:array1[i]];

}

}

}

}

//求并集

for (int i=0;i<array1.count;i++){

for (int j=0; j<array2.count;j++){

if (array1[i]!=array2[j]) {

if (![array containsObject:array1[i]]) {

[array addObject:array1[i]];

}

else if (![array containsObject:array2[j]])

{

[array addObject:array2[j]];

}

}

}

}

//选择排序 

for (int m=0; m<array.count-1;m++){

for (int n=m+1; n<array.count;n++){


int a = [[array objectAtIndex:m] intValue];

int b = [[array objectAtIndex:n] intValue];

if (a> b)

{

[array replaceObjectAtIndex:m withObject:[NSString stringWithFormat:@"%d",b]];

[array replaceObjectAtIndex:n withObject:[NSString stringWithFormat:@"%d",a]];

}

}

}

//冒泡法

for (int i = 0; i<array.count-1;i++){

for (int j=0; j<array.count-i-1;j++){

if ([array[j] intValue] > [array[j+1] intValue]) {

NSNumber* temp = array[j];

[array replaceObjectAtIndex:j withObject:array[j+1]];

[array replaceObjectAtIndex:j+1 withObject:temp];

}

}

}

//插入排序

for (int i = 1; i < array.count ; i++){

int tmp = [[array objectAtIndex:i] intValue];

int j = i-1;

while (j >= 0 &&[ [array objectAtIndex:j]  intValue] > tmp)

{

[array replaceObjectAtIndex:j+1 withObject:[array objectAtIndex:j]];

j--;

}

[array replaceObjectAtIndex:j+1 withObject: [NSString stringWithFormat:@"%d",tmp]];

}

NSLog(@"数组%@",array);

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容