跳到主要内容

选择排序

#include <iostream>
using namespace std;

int main()
{
int cards[13] = {311, 112, 402, 405, 206, 207, 101, 113, 208, 303, 304, 309, 410};
// 枚举每张待插入的牌
for (int i = 0; i < 13; i++)
{
int min = cards[i], min_id = i;
for(int j = i; j < 13; j++)
if(cards[j] < min)
{
min = cards[j];
min_id = j;
}
cards[min_id] = cards[i];
cards[i] = min;
}
for (int i = 0; i < 13; i++)
cout << cards[i] << endl;
return 0;
}

js 实现选择排序:

let example = [8, 94, 15, 88, 55, 76, 21, 39];
function selectSort(arr) {
let len = arr.length;
for (i = 0; i < len - 1; i++) {
let minIndex = i;
for (j = i + 1; j < len; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
let temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
return arr;
}
console.log(selectSort(example));