Skip to content

Instantly share code, notes, and snippets.

@caigen
Created October 19, 2013 10:36
Show Gist options
  • Select an option

  • Save caigen/7054303 to your computer and use it in GitHub Desktop.

Select an option

Save caigen/7054303 to your computer and use it in GitHub Desktop.
大众点评2014在线笔试题。排序:要求所有的奇数排在偶数前面。
#include <cstdlib>
#include <iostream>
using std::swap;
using std::cout;
using std::endl;
template <typename T>
void print(T a[], int n) {
for (int i = 0; i <= n-2; i++) {
cout << a[i] << " ";
}
cout << a[n-1] << endl;
}
// put all the odd numbers before the even numbers.
void my_sort(int a[], int n) {
int i = 0;
int j = n-1;
while (i <= j) {
while (a[i]%2 == 1) {
i++;
}
while (a[j]%2 == 0) {
j--;
}
if (i < j) {
swap(a[i],a[j]);
}
}
}
int main(int argc, char* argv[]) {
int a[5] = {3,4,5,2,0};
my_sort(a,5);
print(a, 5);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment