選擇排序的原理其實和冒泡排序很像,都是兩層循環嵌套:ios
如下 gif 參考http://www.javashuo.com/article/p-dbqzbdfz-nu.html:
markdown
#include <iostream> #include <string> using namespace std; int main(){ int array[10] = {1, 6, 8, 7, 9, 4, 3, 0, 2, 5}; int len = sizeof(array) / sizeof(array[0]); int min_num = 0; // 最小值 int min_index = 0; // 每一輪比較的最小值索引 for (int i = 0; i < len; i++){ min_num = array[i]; min_index = i; for (int j = i + 1; j < len; j++){ if (array[j] < min_num){ min_num = array[j]; min_index = j; // 更新最小值的位置 } } int temp = array[min_index]; array[min_index] = array[i]; array[i] = temp; } for (int i = 0; i < len; i++){ cout << array[i] << " "; } }