从两端开始找,比盲目的从头到尾效率最高快一半
#include<iostream>
using namespace std;
void swap(int a[], int &n) {
int low =0, high=n-1,temp;
while (low<high) {
//队列前开始找女生
while (a[low]==1) low++;
//队列后开始找男生
while (a[high]==2) high--;
// 交换
if (low<high) {
temp= a[low];
a[low]=a[high];
a[high]=temp;
}
}
}
int main() {
// 1是男生,2是女生
int n = 0, i = 0;
const int MAX=5;
int arr[MAX];
while (i<MAX) {
cin>>arr[i];
n++; // 更新人数
i++;
}
swap(arr,n);
cout << "女生在前的排列:" << endl;
for (int i=0;i<n;i++) {
cout<<arr[i]<<" ";
}
return 0;
}