Description
You know sorting is very important. And this easy problem is:
Given you an array with N non-negative integers which are smaller than 10,000,000, you have to sort this array. Sorting means that integer with smaller value presents first.
Input
The first line of the input is a positive integer T. T is the number of the test cases followed.
The first line of each test case is a positive integer N (1<= N<= 1000) which represents the number of integers in the array. After that, N lines followed. The i-th line is the i-th integer in the array.
Output
The output of each test case should consist of N lines. The i-th line is the i-th integer of the array after sorting. No redundant spaces are needed.
考试前写几个排序练练手……用这道题练了一下merge sort和tree sort
#include<cstdio>
#define MAX 1001
int a[MAX], aux[MAX]; void merge_sort(int lo, int hi) {
if (lo < hi) {
int mid = lo + (hi - lo)/;
merge_sort(lo, mid);
merge_sort(mid+, hi); for (int i = lo; i <= hi; ++i)
aux[i] = a[i]; int l = lo, r = mid+;
for (int i = lo; i <= hi; i++) {
if (l > mid) a[i] = aux[r++];
else if (r > hi) a[i] = aux[l++];
else if (aux[r] < aux[l]) a[i] = aux[r++];
else a[i] = aux[l++];
}
}
} int main(int argc, char *argv[]) {
int t, n; scanf("%d", &t); while(t--) {
scanf("%d", &n); for (int i = ; i < n; ++i)
scanf("%d", &a[i]); merge_sort(, n-); for (int i = ; i < n; ++i)
printf("%d\n", a[i]);
} return ;
}
tree sort直接拿以前笔试试卷上的二叉树题目做,所以带了模版。没有平衡,效率不太好(0.02s过)去掉插入操作里的检查重复元素之后就可以允许重复元素了。
#include <iostream>
#include <stack>
using namespace std; template<class Entry>
struct Binary_node {
Entry data;
Binary_node<Entry> *left;
Binary_node<Entry> *right;
bool flag;
Binary_node() { left = NULL; right = NULL; flag = false;}
Binary_node(const Entry &x) { data = x; left = NULL; right = NULL; flag = false;}
}; template<class Entry>
void print(const Entry &x) {
cout << x << '\n';
} template<class Entry>
class Binary_tree {
public:
Binary_tree() {
root = NULL;
} bool insert(const Entry &x) {
return insert(root, x);
} bool insert(Binary_node<Entry>* &r, const Entry &x) {
if (r == NULL) {
r = new Binary_node<Entry>(x); return true;
}
//if (x == r->data) return false;
if (x < r->data) return insert(r->left, x);
return insert(r->right, x);
} void inorder(void (*visit)(const Entry &)) {
std::stack<Binary_node<Entry> *> s;
Binary_node<Entry> *p = root;
while(!(p == NULL && s.empty())) {
while(p != NULL) {
s.push(p);
p = p->left;
} if (s.empty()) return;
p = s.top(); s.pop();
visit(p->data);
p = p->right;
}
} void del() {
delete(root);
} void del(Binary_node<Entry>* &r) {
if (r != NULL) {
if(r->left) del(r->left);
if(r->right) del(r->right);
delete r;
}
}
Binary_node<Entry> *root;
}; int main(int argc, char *argv[]) {
int t, n;
cin >> t;
int num; while(t--) {
cin >> n;
Binary_tree<int> bt;
for (int i = ; i < n; ++i) {
cin >> num;
bt.insert(num);
} bt.inorder(print<int>);
bt.del();
} return ;
}