选择排序|Selection sort
时间复杂度:
$$ O(n^{2}) $$
从下标0元素i开始,让i与后面的元素进行比较,如果有元素大于i则使用index标记该元素,继续与后面的元素比较知道遍历完一次,直到i等于数组的长度
#include <iostream>
using namespace std;
void print_array(int* arr, int size) {
//打印数组
cout << "array={ ";
for (int i = 0; i < size; ++i) {
cout << arr[i] << " ";
}
cout << "}" << endl;
}
void selection_sort(int* arr, int len) {
for (int i = 0; i < len - 1; i++) {
int index = i;
for (int j = i + 1; j < len; j++) {
if (arr[j] < arr[index]) {
index = j;
}
}
if (index != i) {
int tmp = arr[index];
arr[index] = arr[i];
arr[i] = tmp;
}
}
}
int main() {
//数组基本信息
int array1[] = { 55,66,22,11,33,44,88,77,99 };
int sizeArray = sizeof(array1) / sizeof(array1[0]);
//打印数组
print_array(array1,sizeArray);
//对数组进行选择排序
selection_sort(array1, sizeArray);
print_array(array1, sizeArray);
return 0;
}