原理:
代码:
- (void)selectionSort {
int a[] = {7,1,3,5,8,10,9,2,4,6,19,22,0,33};
int length = sizeof(a)/sizeof(a[0]);
printfLog(a,length);
int minIndex;
for (int i = 0; i < length - 1; i++) {
minIndex = i;
for (int j = i + 1; j < length; j++) {
if (a[j] < a[minIndex]) { //寻找最小的数
minIndex = j; //将最小数的索引保存
}
}
swap(&a[i], &a[minIndex]);
}
printfLog(a,length);
}
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
void printfLog(int a[],int length) {
for (int i = 0; i < length; i++) {
printf("%d ",a[i]);
}
printf("\n");
}