桶排序
- (void)bucketSortWithArr:(NSMutableArray*)arr
{
//思路
//1.0 生成对应个数的桶
NSMutableArray *buckerArr =[NSMutableArray arrayWithCapacity:87];
for (int m=0; m<87; m++) {
[buckerArr addObject:@"0"];
}
//2.0 将数据按序号放入桶中
for (int m=0; m<buckerArr.count; m++) {
for (NSString *str in arr)
{
if ([str intValue] == m)
{
[buckerArr replaceObjectAtIndex:m withObject:[NSString stringWithFormat:@"%d",[buckerArr[m]intValue]+1]];
}
}
}
//3.0 遍历桶中数据
//3.1 清空容器
[arr removeAllObjects];
//3.2 遍历顺序添加
for(int m=0; m<buckerArr.count; m++) {
NSString *num = buckerArr[m];
for (int n=0; n< [num intValue]; n++) {
[arr addObject:[NSString stringWithFormat:@"%d",m]];
}
}
NSLog(@"桶排序结果:%@",arr);
}
选择排序
- (void)selectSortWithArr:(NSMutableArray*)arr
{
//思路
//1.0 一轮一轮的找最大值或者最小值
//2.0 把找到的值放到每一轮的最后一个位置
//有多少个数字就要执行多少次
for (int m=0; m<arr.count; m++) {
//记录改组数字中的最大值
int MaxNum = [arr[0] intValue];
//记录最大值索引
int MaxIndex = 0;
//查找该组数字中的最大值
for (int n=0; n< arr.count-m; n++) {
//对比记录最大值 以及 最大值索引
if (MaxNum < [arr[n]intValue]) {
MaxNum = [arr[n]intValue];
MaxIndex = n;
}
//查找完成把最大值和改组数据最后一个数字换位
if (n == arr.count - m -1) {
//将最大值位置的数字修改为最后一个数字
arr[MaxIndex] = arr[n];
//将最后一个数字修改为最大值
arr[n] = [NSString stringWithFormat:@"%d",MaxNum];
}
}
}
NSLog(@"选择排序结果:%@",arr);
}
插入排序
- (void)insertSortWithArr:(NSMutableArray*)arr
{
//思路
//1.0 拿每一个元素和已经有顺序的一组元素对比
//2.0 如果比已有的小,则换位
for (int m=1; m<arr.count; m++)
{
NSString *currentStr = arr[m];
for(int n=0; n<m; n++)
{
if ([currentStr intValue] < [arr[n]intValue])
{
[arr exchangeObjectAtIndex:n withObjectAtIndex:m];
}
}
}
NSLog(@"插入排序结果:%@",arr);
}
冒泡排序
- (void)contrastSortWithArr:(NSMutableArray*)arr
{
//思路
//1.0 有多少个数字进行多少轮换位
for (int m=0; m<arr.count; m++) {
//2.0 每一轮遍历一遍剩余的数字
for (int n=0; n<arr.count-m-1; n++) {
NSString *currentStr = arr[n];
NSString *nextStr = arr[n+1];
//如果当前数字比下一个数字大则换位
if ([currentStr intValue] > [nextStr intValue]) {
[arr exchangeObjectAtIndex:n withObjectAtIndex:n+1];
}
}
}
NSLog(@"冒泡排序结果:%@",arr);
}
快速排序
- (void)fastSortWithArr:(NSMutableArray*)arr WithLeft:(int)left WithRight:(int)right
{
NSLog(@"快速排序结果:%@",arr);
if(left < right)
{
int m = left;
int n = right;
int key = [arr[left]intValue];
while (m < n)
{
//从右边找到比KEY大的
while ([arr[n]intValue]>key)
{
n--;
}
//从左边找到比KEY小的
while ([arr[m]intValue] < key)
{
m ++;
}
//交换位置
[arr exchangeObjectAtIndex:m withObjectAtIndex:n];
}
//将基准值归位
arr[m] = [NSString stringWithFormat:@"%d",key];
//分两组从新开始
[self fastSortWithArr:arr WithLeft:left WithRight:m-1];
[self fastSortWithArr:arr WithLeft:m+1 WithRight:right];
}
}
转载于:https://www.cnblogs.com/yangthinker/p/9944812.html
相关资源:JAVA上百实例源码以及开源项目