用oc/c编写插入排序

-(NSArray*)insertSortWithArray:(NSArray *)oldArray{
         NSMutableArray *newArray =[[NSMutableArray alloc]initWithArray:oldArray];

         int num = [newArray count];

         for (int i = 1; i < num ; i++)

        {
              int tmp = [[newArray objectAtIndex:i] intValue];
              int j = i-1;
             while (j >= 0 &&[ [newArray objectAtIndex:j]  intValue] > tmp)

             {
                  [newArray replaceObjectAtIndex:j+1 withObject:[newArray objectAtIndex:j]];
                  j--;
             }
            [newArray replaceObjectAtIndex:j+1 withObject: [NSString stringWithFormat:@"%d",tmp]];
      }
      NSLog(@"插入排序后的结果:%@",[newArray description]);
      return [data autoRelease];
}

 

 

void insert_Sort(int a[], int n)

{

        int i , j , tmp;

        for( i = 2 ;i < n; i++)

       {

                tmp = a[i];

                for( j = i - 1; j > 0 && tmp < a[j] ; j--)   

                {     

                        a[j+1] = a[j];

                }

                a[j+1] = tmp;

         }

 

}

你可能感兴趣的:(插入排序)