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(@"數(shù)組%@",array);

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容