练手写了简答选择排序代码如下:
#include <iostream>
#include <array>
using namespace std;
#define DEBUG 1
template <typename T>
void swap_pos(T &a, T &b){
#if DEBUG
cout << a << " " << b << endl;
#endif
a ^= b;
#if DEBUG
cout << a << " " << b << endl;
#endif
b ^= a;
#if DEBUG
cout << a << " " << b << endl;
#endif
a ^= b;
#if DEBUG
cout << a << " " << b << endl;
#endif
}
template <typename T>
void printArr(T const& arr){
for(auto it = arr.begin(); it != arr.end(); it++){
cout << *it << " ";
}
}
template <typename T>
void selectSort(T& arr){
int nSize = arr.size();
//add one elem as min_holder
int min_pos = 0;
for(int i=0; i<nSize; i++){
min_pos = i;
for(int j=i+1; j<nSize; j++){
if(arr[min_pos] > arr[j]){
min_pos = j;
}
}
swap_pos(arr[i],arr[min_pos]); //bug at i=3, min_pos=3 for some reason
#if DEBUG
printArr(arr); cout << "\n";
#endif
}
}
int main(){
array<int, 10> og_arr = {2,3,4,1,5,6,9,8,7,0};
array<int, 10> arr(og_arr);
selectSort(arr);
printArr(arr);
}
swap_pos 会在 i,min_pos 均为3的循环出错,打出信息如下:
compiler:gcc version 8.1.0 (x86_64-posix-seh-rev0, Built by MinGW-W64 project)
还请高人指点这是哪方面的问题,多谢!