Skip to content

Instantly share code, notes, and snippets.

@cshijiel
Last active August 11, 2017 06:40
Show Gist options
  • Save cshijiel/6a3ee6b79972e7455e9d2233da65910b to your computer and use it in GitHub Desktop.
Save cshijiel/6a3ee6b79972e7455e9d2233da65910b to your computer and use it in GitHub Desktop.
冒泡排序、奇偶排序
#include <iostream>
using namespace std;
int main() {
int a[10];
for (int i = 0; i < 10; ++i) {
cin >> a[i];
}
// 首先,我们把奇数放到数组左边,偶数放到数组右边
int l = 0, r = 9;
while (l <= r) {
bool leftIsOdd = a[l] % 2 == 1;
bool rightIsEven = a[r] % 2 == 0;
if (leftIsOdd) {
l++;
} else if (rightIsEven) {
r--;
} else if (!leftIsOdd && !rightIsEven) {
int temp = a[l];
a[l] = a[r];
a[r] = temp;
}
}
// 对l左边(奇数部分)冒泡,不断比较相邻的两个数,如果顺序错了,那么就交换
int start = 0, end = l;
for (int i = start; i < end - 1; i++) {
for (int j = start + 1; j < start + end - i; j++) {
if (a[j - 1] > a[j]) {
int temp = a[j];
a[j] = a[j - 1];
a[j - 1] = temp;
}
}
}
// 对l右边(偶数部分)冒泡,不断比较相邻的两个数,如果顺序错了,那么就交换
start = l, end = 10;
for (int i = start; i < end - 1; i++) {
for (int j = start + 1; j < start + end - i; j++) {
if (a[j - 1] > a[j]) {
int temp = a[j];
a[j] = a[j - 1];
a[j - 1] = temp;
}
}
}
for (int i = 0; i < 10; i++) {
cout << a[i] << ' ';
}
return 0;
}
#include <iostream>
using namespace std;
int main() {
int a[10];
for (int i = 0; i < 10; i++) {
cin >> a[i];
}
// 冒泡,不断比较相邻的两个数,如果顺序错了,那么就交换
for (int i = 0; i < 9; i++) {
for (int j = 1; j < 10 - i; j++) {
// 与刚才的冒泡排序不同,我们不只是通过较数字的大小决定顺序
// 如果左边的为偶数,右边的为奇数,那么顺序也需要颠倒
bool leftIsEven = a[j - 1] % 2 == 0;
bool rightIsEven = a[j] % 2 == 0;
if ((leftIsEven && !rightIsEven) ||
(leftIsEven == rightIsEven && a[j - 1] > a[j])) {
int temp = a[j];
a[j] = a[j - 1];
a[j - 1] = temp;
}
}
}
for (int i = 0; i < 10; i++) {
cout << a[i] << ' ';
}
return 0;
}
#include <iostream>
using namespace std;
int main() {
int n, a[1000];
cin >> n;
// 输入n个数
for (int i = 0; i < n; ++i) {
cin >> a[i];
}
// 冒泡,不断比较相邻的两个数,如果顺序错了,那么就交换
for (int i = 0; i < n - 1; ++i) {
for (int j = 0; j < n - i; ++j) {
if (a[j - 1] > a[j]) {
int temp = a[j - 1];
a[j - 1] = a[j];
a[j] = temp;
}
}
}
// 依次输出
for (int i = 0; i < n; ++i) {
cout << a[i] << endl;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment