//函数声明
void insertion_sort(int array[], int first, int last);
int array[11] = {23, 8, 90, 12, 7, -9, 54, 3, 36, 99, -17};
//调用
insertion_sort(array, 0, 10);
printf("sort result:");
for (int p = 0; p < 11; p++) {
printf(" %d", array[p]);
}
printf("\n");
//sort result: -17 -9 3 7 8 12 23 36 54 90 99
void insertion_sort(int array[], int first, int last) {
int i = 0, j = 0;
int temp = 0;
for(i = first + 1; i <= last; i++)
{
temp = array[i];
j = i - 1;
//array[j]大于temp的数时,把大于temp的数向后移动一位到array[j+1],然后把temp放在array[j]处
//与已排序的数逐一比较,大于temp时,该数移后
while((j >= 0) && (array[j] > temp))
{
array[j+1] = array[j];
j--;
}
//存在大于temp的数 把temp放在前面的位置
if(j!=i-1) {
array[j+1] = temp;
}
}
}
_dataArray = [NSMutableArray arrayWithObjects:@21, @3, @34, @(-28), @10, @(-33), @54, @9, @0, @(-2), nil];
//调用
[self insertSort];
NSString *string = [self.dataArray componentsJoinedByString:@" "];
NSLog(@"sort result : %@", string);
//sort result : -33 -28 -2 0 3 9 10 21 34 54
- (void)insertSort {
NSInteger i = 0, j = 0;
NSInteger temp = 0;
for (int k = 0; k < self.dataArray.count; k++) {
NSNumber *number = [NSNumber numberWithInteger:[self.dataArray[k] integerValue]];
self.dataArray[k] = number;
}
for (i = 1; i < self.dataArray.count; i++) {
temp = [self.dataArray[i] integerValue];
j = i - 1;
while ((j >= 0) && ([self.dataArray[j] integerValue] > temp)) {
self.dataArray[j+1] = self.dataArray[j];
j--;
}
if (j != i-1) {
self.dataArray[j+1] = [NSNumber numberWithInteger:temp];
}
}
}
var dataArray:NSMutableArray = [76, 1, 19, -4, 2, 4, 6, 8, 0, -19];
//调用
self.insertSort();
let string:NSString = dataArray.componentsJoinedByString(" ");
NSLog("sort result: %@", string);
//sort result: -19 -4 0 1 2 4 6 8 19 76
func insertSort() {
var j:NSInteger = 0;
var temp:NSInteger = 0;
for k:NSInteger in 0 ..< dataArray.count {
let currentNumber:NSNumber = NSNumber.init(integer: dataArray[k].integerValue);
dataArray[k] = currentNumber;
}
for i:NSInteger in 1..<dataArray.count {
temp = dataArray[i].integerValue;
j = i - 1;
while ((j >= 0) && (dataArray[j].integerValue > temp)) {
dataArray[j+1] = dataArray[j];
j-=1;
}
if j != (i-1) {
dataArray[j+1] = NSNumber.init(integer: temp);
}
}
}