標籤:upload net sizeof copyright idt .com rda span ext
?選擇排序:
每一趟從待排序的資料元素中選出最小(或最大)的一個元素,順序放在已排好序的數列的最後。直到所有待排序的資料元素排完。
選擇排序是不穩定的排序方法。
一. 演算法描寫敘述
選擇排序:比方在一個長度為N的無序數組中。在第一趟遍曆N個資料,找出當中最小的數值與第一個元素交換,第二趟遍曆剩下的N-1個資料,找出當中最小的數值與第二個元素交換......第N-1趟遍曆剩下的2個資料,找出當中最小的數值與第N-1個元素交換。至此選擇排序完畢。
以以下5個無序的資料為例:
56 12 80 91 20(文中僅細化了第一趟的選擇過程)
第1趟:12 56 80 91 20
第2趟:12 20 80 91 56
第3趟:12 20 56 91 80
第4趟:12 20 56 80 91
???代碼實現:
// main.m
// 演算法----選擇排序
// Created by lanouhn on 14-9-16.
// Copyright (c) 2014年 [email protected] All rights reserved.
#import<Foundation/Foundation.h>
int main(int argc,const char * argv[])
{
int array[] = {12,2, 6, 9, 8, 5, 7, 1, 4};
//為了添加可移植性(採取sizeof())計算數組元素個數count
int count = sizeof(array) /sizeof(array[0]);
//
for (int i = 0; i < count -1; i++) { //比較的趟數
int minIndex = i;//尋找最小值
for (int j = minIndex +1; j < count; j++ ) {
if (array[minIndex] > array[j]) {
minIndex = j;
}
}
//假設沒有比較到最後還剩餘一個數,那麼就運行以下的操作
if (minIndex != i) {
//交換資料
int temp = 0;
temp = array[i];
array[i] = array[minIndex];
array[minIndex] = temp;
}
}
for (int i = 0; i < count; i++) {
printf("[%2d]: %d\n", i, array[i]);
}
return 0;
}
IOS演算法(二)之選擇排序