Polycarp likes to play with numbers. He takes some integer number $x$, writes it down on the board, and then performs with it $n - 1$ operations of the two kinds:   divide the number $x$ by $3$ ($x$ must be divisible by $3$);  multiply the number $x$ by $2$. 

After each operation, Polycarp writes down the result on the board and replaces $x$ by the result. So there will be $n$ numbers on the board after all.

You are given a sequence of length $n$ — the numbers that Polycarp wrote down. This sequence is given in arbitrary order, i.e. the order of the sequence can mismatch the order of the numbers written on the board.

Your problem is to rearrange (reorder) elements of this sequence in such a way that it can match possible Polycarp's game in the order of the numbers written on the board. I.e. each next number will be exactly two times of the previous number or exactly one third of previous number.

It is guaranteed that the answer exists.


-----Input-----

The first line of the input contatins an integer number $n$ ($2 \le n \le 100$) — the number of the elements in the sequence. The second line of the input contains $n$ integer numbers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 3 \cdot 10^{18}$) — rearranged (reordered) sequence that Polycarp can wrote down on the board.


-----Output-----

Print $n$ integer numbers — rearranged (reordered) input sequence that can be the sequence that Polycarp could write down on the board.

It is guaranteed that the answer exists.


-----Examples-----
Input
6
4 8 6 3 12 9

Output
9 3 6 12 4 8 

Input
4
42 28 84 126

Output
126 42 84 28 

Input
2
1000000000000000000 3000000000000000000

Output
3000000000000000000 1000000000000000000 



-----Note-----

In the first example the given sequence can be rearranged in the following way: $[9, 3, 6, 12, 4, 8]$. It can match possible Polycarp's game which started with $x = 9$.

Difficulty: MEDIUM
Tags: Sorting

Graph traversal

Mathematics
Skill types: Sorting

Starter code:

Solutions:
from sys import stdin, stdout

def rearrage_polycarp(n: int, sequence):
	polys_seq = set(sequence)
	ordered_seq = [num for num in sequence if not (num % 2 == 0 and num // 2 in polys_seq or 3 * num in polys_seq)]
	n -= 1
	i = 0
	while n:
		if 2 * ordered_seq[i] in polys_seq:
			ordered_seq.append(2 * ordered_seq[i])
		else:
			ordered_seq.append(ordered_seq[i] // 3)
		n -= 1
		i += 1
	return ordered_seq
n = int(stdin.readline().rstrip())
sequence = [int(x) for x in stdin.readline().rstrip().split(' ')]
stdout.write(' '.join((str(num) for num in rearrage_polycarp(n, sequence))) + '\n')


from sys import stdin
from collections import defaultdict

def main():
	(n,) = stdin_get_ints_from_line()
	a = []
	r = defaultdict(int)
	for x in stdin.readline().split(' '):
		xx = int(x)
		a.append(xx)
		r[xx] += 1
	num = a[0]
	direction = 1
	result = []
	result.append(num)
	for _ in range(n - 1):
		if direction == 1:
			if num != 3 and num % 3 == 0 and (r[num // 3] > 0):
				result.append(num // 3)
				r[num // 3] -= 1
				num = num // 3
			elif r[num * 2] > 0:
				result.append(num * 2)
				r[num * 2] -= 1
				num = num * 2
			else:
				direction = -1
				if len(result) > 0:
					num = result[0]
		if direction == -1:
			if r[num * 3] > 0:
				result.insert(0, num * 3)
				r[num * 3] -= 1
				num = num * 3
			elif num % 2 == 0 and r[num // 2] > 0:
				result.insert(0, num // 2)
				r[num // 2] -= 1
				num = num // 2
			else:
				raise RuntimeError()
	print(' '.join((str(d) for d in result)))

def stdin_get_ints_from_line():
	return (int(x) for x in stdin.readline().strip().split(' '))

def stdin_get_ints_list_from_line():
	return list((int(x) for x in stdin.readline().strip().split(' ')))

def stdin_get_string_from_line():
	return stdin.readline().strip()
main()


import sys
data = sys.stdin.readlines()
lis = []
for line in data:
	lis.append(line)
n = lis[0].split()[0]
n = int(n)
seq = list(map(int, lis[1].split()))

def e2e3(n):
	n1 = n
	bn = bin(n)[2:]
	e2 = len(bn) - (bn.rfind('1') + 1)
	e3 = 0
	n = n >> e2
	while n % 3 == 0:
		n = n // 3
		e3 += 1
	return (e2, -e3, n1)
seq = [e2e3(n) for n in seq]
seq.sort()
for n in seq:
	print(n[-1], end=' ')


n = int(input())
l = list(map(int, input().split()))
m = []
for i in range(n):
	for k in l:
		if k * 2 in l or (k // 3 in l and k % 3 == 0):
			pass
		else:
			m.append(k)
			l.remove(k)
print(*m[::-1])


def bakchodi(x):
	cnt = 0
	while x % 3 == 0:
		x = x // 3
		cnt += 1
	return cnt
n = int(input())
ls = [int(x) for x in input().split()]
for j in range(n):
	for i in range(n - 1):
		if bakchodi(ls[i]) < bakchodi(ls[i + 1]):
			(ls[i], ls[i + 1]) = (ls[i + 1], ls[i])
		elif bakchodi(ls[i]) == bakchodi(ls[i + 1]):
			if ls[i] > ls[i + 1]:
				(ls[i], ls[i + 1]) = (ls[i + 1], ls[i])
for i in ls:
	print(i, end=' ')


def traverse(num, nums, position):
	copy = nums[:]
	position = position[:]
	if num not in copy:
		return []
	else:
		copy.remove(num)
		position.append(num)
		if len(copy) == 0:
			return position
		elif num % 3 == 0:
			a = traverse(num // 3, copy, position)
			b = traverse(num * 2, copy, position)
			if len(a) > 0:
				return a
			else:
				return b
		else:
			return traverse(num * 2, copy, position)
numbers = int(input())
nums = [int(x) for x in input().split(' ')]
for i in nums:
	total = traverse(i, nums, [])
	if len(total) > 0:
		print(' '.join([str(x) for x in total]))
		break


from math import gcd

def gce(x):
	ret = x[0]
	for i in x:
		ret = gcd(ret, i)
	return ret
n = int(input())
a = list(map(int, input().split()))
g = gce(a)
a = [i // g for i in a]
b = []
for i in range(n):
	d = [0, 0]
	c = a[i]
	while c % 2 == 0:
		c //= 2
		d[0] += 1
	while c % 3 == 0:
		c //= 3
		d[1] += 1
	b.append(d)
b.sort(key=lambda x: x[0])
b.sort(reverse=True, key=lambda x: x[1])
ans = []
for i in range(n):
	ans.append(str(2 ** b[i][0] * 3 ** b[i][1] * g))
print(' '.join(ans))


import math
import sys, collections
from sys import stdin, stdout

def get_ints():
	return map(int, sys.stdin.readline().strip().split())

def get_array():
	return list(map(int, sys.stdin.readline().strip().split()))

def get_string():
	return sys.stdin.readline().strip()

def input():
	return sys.stdin.readline().strip()

def file():
	sys.stdin = open('input.py', 'r')
	sys.stdout = open('output.py', 'w')

def is_subsequence(x, y):
	x = list(x)
	for letter in y:
		if x and x[0] == letter:
			x.pop(0)
	return not x

def sieve():
	spf[1] = 1
	for i in range(2, MAXN):
		spf[i] = i
	for i in range(4, MAXN, 2):
		spf[i] = 2
	for i in range(3, mt.ceil(mt.sqrt(MAXN))):
		if spf[i] == i:
			for j in range(i * i, MAXN, i):
				if spf[j] == j:
					spf[j] = i

def getFactorization(x):
	ret = list()
	while x != 1:
		ret.append(spf[x])
		x = x // spf[x]
	return ret

def getFloor(A, x):
	(left, right) = (0, len(A) - 1)
	(ind, floor) = (-1, -1)
	while left <= right:
		mid = (left + right) // 2
		if x < A[mid]:
			right = mid - 1
		else:
			floor = A[mid]
			ind = mid
			left = mid + 1
	return ind
mod = 10 ** 9 + 7

def main():
	n = int(input())
	l = get_array()
	l.sort()
	for i in range(n):
		ll = l[:]
		ans = []
		ans.append(ll[i])
		ll.pop(i)
		while len(ll) != 0:
			if ans[-1] * 2 in ll:
				ll.pop(ll.index(ans[-1] * 2))
				ans.append(ans[-1] * 2)
			elif ans[-1] // 3 in ll:
				ll.pop(ll.index(ans[-1] // 3))
				ans.append(ans[-1] // 3)
			else:
				break
		if len(ans) == n:
			print(*ans)
			break
main()


n = int(input())
a = list(map(int, input().split()))
pool = set(a)

def check(pool, start, path=None):
	pool.remove(start)
	if path is None:
		path = []
	if not pool:
		return path + [start]
	else:
		if not start % 3 and start // 3 in pool:
			return check(pool.copy(), start // 3, path + [start])
		if start * 2 in pool:
			return check(pool.copy(), start * 2, path + [start])
for i in range(n):
	res = check(set(pool), a[i])
	if res is not None:
		print(*res)
		break


n = int(input())
lst = [int(x) for x in input().split()]
n = len(lst)

def sol(lst):
	res = []
	for i in range(n):
		tempLst = lst.copy()
		res += [lst[i]]
		tempLst.remove(lst[i])
		for j in range(1, n):
			for k in range(len(tempLst)):
				if tempLst[k] == res[len(res) - 1] * 2:
					res += [tempLst[k]]
					tempLst.remove(tempLst[k])
					break
				elif res[len(res) - 1] / 3 % 1 == 0 and tempLst[k] == res[len(res) - 1] // 3:
					res += [tempLst[k]]
					tempLst.remove(tempLst[k])
					break
		if len(res) == n:
			for i in res:
				print(str(i) + ' ', end='')
			return
		else:
			res = []
	print(str(111))
sol(lst)


n = int(input().strip())
nums = list(map(int, input().strip().split()))
visited = [0] * n

def dfs(i):
	res = []
	flag = True
	for j in range(n):
		if not visited[j]:
			if nums[i] % 3 == 0 and nums[j] == nums[i] // 3 or nums[j] == nums[i] * 2:
				flag = False
				visited[j] = 1
				tmp = dfs(j)
				visited[j] = 0
				if isinstance(tmp[0], list):
					for item in tmp:
						res.append([nums[i]] + item)
				else:
					res.append([nums[i]] + tmp)
	if flag:
		res = [nums[i]]
	return res
for i in range(n):
	visited[i] = 1
	ans = dfs(i)
	visited[i] = 0
	if not isinstance(ans[0], list):
		continue
	for j in range(len(ans)):
		cur = ans[j]
		if len(cur) == n:
			cur = list(map(str, cur))
			print(' '.join(cur))
			i = n + 1
			break


n = int(input())
L = list(map(int, input().split()))
aux = []

def dook(n):
	if n % 3 == 0 and n // 3 in L:
		aux.append(n // 3)
		dook(n // 3)
	elif n * 2 in L:
		aux.append(n * 2)
		dook(n * 2)
for i in range(n):
	dook(L[i])
	if len(aux) == n - 1:
		aux.insert(0, L[i])
		break
	del aux[:]
for x in aux:
	print(x, end=' ')


def func(num):
	cnt = 0
	while num % 3 == 0:
		num //= 3
		cnt += 1
	return cnt
n = int(input())
arr = list(map(int, input().split()))
d = {}
val = []
for i in arr:
	x = func(i)
	if x in d:
		d[x].append(i)
	else:
		d[x] = [i]
		val.append(x)
val.sort()
val = val[-1::-1]
ans = []
for i in val:
	temp = d[i]
	temp.sort()
	ans += temp
print(*ans)


n = int(input(''))
arr = list(map(int, input().split()))
arr.sort()
sol = []
for i in range(n):
	sol.append([0, arr[i]])
for i in range(n):
	cnt = 0
	while arr[i] % 3 == 0:
		cnt += 1
		arr[i] = arr[i] // 3
	sol[i][0] = cnt
sol = sorted(sol, key=lambda x: x[0], reverse=True)
ans = []
for i in range(n):
	ans.append(sol[i][1])
print(*ans)


import math
from collections import defaultdict
from sys import stdin, stdout
input = stdin.readline

def main():
	n = int(input())
	a = list(map(int, input().split()))

	def deg3(x):
		res = 0
		while x % 3 == 0:
			x //= 3
			res += 1
		return res
	b = [(-deg3(x), x) for x in a]
	b.sort()
	print(' '.join((str(y) for (x, y) in b)))
main()


input()
a = [int(s) for s in input().split()]
b = [a[0]]
while True:
	k = b[-1]
	x = k * 2
	if x in a:
		b.append(x)
	elif k % 3 == 0:
		x = k // 3
		if x in a:
			b.append(x)
		else:
			break
	else:
		break
while True:
	k = b[0]
	x = k * 3
	if x in a:
		b.insert(0, x)
	elif k % 2 == 0:
		x = k // 2
		if x in a:
			b.insert(0, x)
		else:
			break
	else:
		break
print(' '.join([str(i) for i in b]))


from collections import defaultdict

def possible(start, Dict, n, lis):
	if len(lis) == n:
		print(*lis)
		return lis
	if start % 3 == 0 and Dict[start // 3]:
		ans1 = possible(start // 3, Dict, n, lis + [start // 3])
	elif Dict[start * 2] > 0:
		ans2 = possible(start * 2, Dict, n, lis + [start * 2])
n = int(input())
arr = [int(i) for i in input().split()]
Dict = defaultdict(int)
for i in arr:
	Dict[i] += 1
for star in arr:
	possible(star, Dict, n, [star])


import collections

def solve(n, xs):
	ys = set(xs)
	zs = collections.deque()
	zs.append(ys.pop())
	while ys:
		x = zs[len(zs) - 1]
		if x // 3 in ys:
			ys.remove(x // 3)
			zs.append(x // 3)
		elif 2 * x in ys:
			ys.remove(2 * x)
			zs.append(2 * x)
		else:
			break
	while ys:
		x = zs[0]
		if x // 2 in ys:
			ys.remove(x // 2)
			zs.appendleft(x // 2)
		elif 3 * x in ys:
			ys.remove(3 * x)
			zs.appendleft(3 * x)
		else:
			break
	return zs

def main():
	n = int(input())
	xs = [int(x) for x in input().split()]
	print(*solve(n, xs))

def __starting_point():
	main()
__starting_point()


import sys
from functools import lru_cache
from heapq import merge, heapify, heappop, heappush
from math import ceil, floor, gcd, fabs, factorial, fmod, sqrt, inf
from collections import defaultdict as dd, deque, Counter as c
from itertools import combinations as comb, permutations as perm
from bisect import bisect_left as bl, bisect_right as br, bisect
mod = pow(10, 9) + 7
mod2 = 998244353

def data():
	return sys.stdin.readline().strip()

def out(var):
	sys.stdout.write(str(var))

def outln(var):
	sys.stdout.write(str(var) + '\n')

def l():
	return list(sp())

def sl():
	return list(ssp())

def sp():
	return map(int, data().split())

def ssp():
	return map(str, data().split())

def l1d(n, val=0):
	return [val for i in range(n)]

def l2d(n, m, val=0):
	return [l1d(n, val) for j in range(m)]

def dfs(source):
	res.append(source)
	if len(graph[source]) == 0:
		return res
	for i in graph[source]:
		dfs(i)
mat = []
n = int(data())
arr = l()
arr.sort()
s = set(arr[:])
graph = dd(set)
stack = deque()
stack.append(arr[0])
while stack:
	temp = stack.pop()
	(two, three) = (temp * 2, temp // 3)
	a = 0
	if two <= arr[-1] and two in s:
		graph[temp].add(two)
		if two not in graph.keys():
			stack.append(two)
		a += 1
	if temp % 3 == 0 and three >= arr[0] and (three in s):
		graph[temp].add(three)
		if three not in graph.keys():
			stack.append(three)
		a += 1
	if a == 0:
		graph[temp] = set()
	if temp * 3 not in graph.keys() and temp * 3 <= arr[-1] and (temp * 3 in s):
		stack.append(temp * 3)
	if temp // 2 not in graph.keys() and temp // 2 >= arr[0] and (temp // 2 in s):
		stack.append(temp // 2)
res = []
for i in arr:
	res = []
	dfs(i)
	if len(res) == n:
		break
print(*res)


def get_power(n, k):
	p = 0
	while n % k == 0:
		n //= k
		p += 1
	return p
n = int(input())
a = [[int(n), get_power(int(n), 3), get_power(int(n), 2)] for n in input().split()]
a.sort(key=lambda e: e[2])
a.sort(key=lambda e: e[1], reverse=True)
print(' '.join([str(e[0]) for e in a]))


n = int(input())
a = list(map(int, input().split()))
x = 0
r = []
for i in range(n):
	ok = True
	r = []
	x = a[i]
	r.append(x)
	while ok:
		ok = False
		if x % 3 == 0:
			if x // 3 in a:
				ok = True
				x = x // 3
				r.append(x)
		if x * 2 in a:
			ok = True
			x = x * 2
			r.append(x)
	if len(r) == n:
		break
print(' '.join(map(str, r)))


def f(x):
	global a
	if len(ans) == n:
		print(' '.join(map(str, ans)))
		exit()
	if x % 3 == 0 and x // 3 in a:
		ans.append(x // 3)
		f(x // 3)
		ans.pop()
	if x * 2 in a:
		ans.append(x * 2)
		f(x * 2)
		ans.pop()
n = int(input())
a = list(map(int, input().split()))
ans = []
for i in range(n):
	ans.append(a[i])
	f(a[i])
	ans.pop()


n = int(input())
s = list(map(int, input().split()))
st = set(s)
for i in range(n):
	st1 = st.copy()
	l = 0
	x = s[i]
	ans = []
	while l < n:
		if x % 3 == 0 and x // 3 in st1:
			ans.append(x)
			st1.remove(x)
			x = x // 3
		elif x * 2 in st1:
			ans.append(x)
			st1.remove(x)
			x = x * 2
		else:
			ans.append(x)
			break
	if len(ans) == n:
		break
for i in ans:
	print(i, end=' ')


def cal(v):
	r = 0
	while v % 3 == 0:
		v //= 3
		r -= 1
	while v % 2 == 0:
		v //= 2
		r += 1
	return r
input()
a = list(map(int, input().split()))
a = sorted(a, key=cal)
print(*a)


o = int(input())
l = list(map(int, input().split()))
current = min(l)
forwards = [current]
step = 1
while True and len(forwards) < o:
	if current * 2 in l and current * 2 not in forwards:
		current = current * 2
		forwards.append(current)
	elif current % 3 == 0:
		n = current // 3
		if n in l and n not in forwards:
			current = n
			forwards.append(current)
		else:
			break
	else:
		break
current = min(l)
backwards = []
while True and len(forwards) + len(backwards) < o:
	if current % 2 == 0 and current // 2 in l and (current // 2 not in backwards):
		current = current // 2
		backwards.append(current)
	elif current * 3 in l and current * 3 not in backwards:
		current *= 3
		backwards.append(current)
	else:
		break
print(' '.join((str(x) for x in backwards[::-1] + forwards)))


from collections import deque

def perebor(num):
	for i in range(len(a)):
		if (a[i] / num == 2.0 or num / a[i] == 3.0) and visited[i] == 0:
			visited[i] = 1
			mass.append(a[i])
			perebor(a[i])
			visited[i] = 0
	if visited.count(0):
		mass.pop()
		visited[visited.index(0)] = 0
	else:
		for i in range(len(mass)):
			print(mass[i], end=' ')
		exit(0)
input()
a = [int(i) for i in input().split()]
for i in range(len(a)):
	visited = [0 for j in range(len(a))]
	visited[i] = 1
	mass = deque([a[i]])
	perebor(a[i])


n = int(input())
a = list(map(int, input().split()))
ans = []
while len(a) > 0:
	for k in range(38, -1, -1):
		subans = []
		for x in a[:]:
			if x % 3 ** k == 0:
				subans = subans + [x]
				a.remove(x)
		ans = ans + sorted(subans)
print(*ans)


import sys
input = sys.stdin.readline
from math import ceil, floor

def swaparr(arr, a, b):
	temp = arr[a]
	arr[a] = arr[b]
	arr[b] = temp

def gcd(a, b):
	if a == 0:
		return b
	return gcd(b % a, a)

def nCr(n, k):
	if k > n - k:
		k = n - k
	res = 1
	for i in range(k):
		res = res * (n - i)
		res = res / (i + 1)
	return int(res)

def upper_bound(a, x, lo=0):
	hi = len(a)
	while lo < hi:
		mid = (lo + hi) // 2
		if a[mid] < x:
			lo = mid + 1
		else:
			hi = mid
	return lo

def primefs(n):
	primes = {}
	while n % 2 == 0:
		primes[2] = primes.get(2, 0) + 1
		n = n // 2
	for i in range(3, int(n ** 0.5) + 2, 2):
		while n % i == 0:
			primes[i] = primes.get(i, 0) + 1
			n = n // i
	if n > 2:
		primes[n] = primes.get(n, 0) + 1
	return primes

def power(x, y, p):
	res = 1
	x = x % p
	if x == 0:
		return 0
	while y > 0:
		if y & 1 == 1:
			res = res * x % p
		y = y >> 1
		x = x * x % p
	return res

def swap(a, b):
	temp = a
	a = b
	b = temp
	return (a, b)

def find(x, link):
	p = x
	while p != link[p]:
		p = link[p]
	while x != p:
		nex = link[x]
		link[x] = p
		x = nex
	return p

def union(x, y, link, size):
	x = find(x, link)
	y = find(y, link)
	if size[x] < size[y]:
		(x, y) = swap(x, y)
	if x != y:
		size[x] += size[y]
		link[y] = x

def sieve(n):
	prime = [True for i in range(n + 1)]
	p = 2
	while p * p <= n:
		if prime[p] == True:
			for i in range(p * p, n + 1, p):
				prime[i] = False
		p += 1
	return prime
MAXN = int(1000000.0 + 5)

def spf_sieve():
	spf[1] = 1
	for i in range(2, MAXN):
		spf[i] = i
	for i in range(4, MAXN, 2):
		spf[i] = 2
	for i in range(3, ceil(MAXN ** 0.5), 2):
		if spf[i] == i:
			for j in range(i * i, MAXN, i):
				if spf[j] == j:
					spf[j] = i

def factoriazation(x):
	ret = {}
	while x != 1:
		ret[spf[x]] = ret.get(spf[x], 0) + 1
		x = x // spf[x]
	return ret

def int_array():
	return list(map(int, input().strip().split()))

def str_array():
	return input().strip().split()
MOD = int(1000000000.0) + 7
CMOD = 998244353
INF = float('inf')
NINF = -float('inf')
n = int(input())
a = sorted(int_array())
three = []
for (j, i) in enumerate(a):
	count = 0
	while i % 3 == 0 and i > 0:
		count += 1
		i //= 3
	three.append((-count, j))
three.sort()
ans = []
for i in three:
	(x, y) = i
	if x < 0:
		ans.append(a[y])
		a[y] = None
for i in a:
	if i != None:
		ans.append(i)
print(*ans)


import sys
try:
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
except Exception as es:
	pass
n = int(input())
lst = list(map(int, input().split()))
ans = []
for i in range(n):
	for a in lst:
		if a * 2 in lst or (a % 3 == 0 and a // 3 in lst):
			continue
		else:
			ans.append(a)
			lst.remove(a)
print(' '.join([str(x) for x in ans[::-1]]))


n = int(input())
l = sorted([int(x) for x in input().split()])
m = l[-1]
a = []
b = []

def solve_before(l, m, k):
	if k > m or k not in l or k in b:
		return False
	b.append(k)
	if k % 2 == 0:
		if not solve_before(l, m, k // 2):
			solve_before(l, m, k * 3)
	else:
		solve_before(l, m, k * 3)
	return True

def solve_after(l, m, k):
	if k > m or k not in l or k in a:
		return False
	a.append(k)
	if k % 3 == 0:
		if not solve_after(l, m, k // 3):
			solve_after(l, m, k * 2)
	else:
		solve_after(l, m, k * 2)
	return True
solve_before(l, m, m)
solve_after(l, m, m)
ans = list(reversed(b)) + a[1:]
print(' '.join((str(x) for x in ans)))


def cal(v):
	cnt = 0
	while v % 3 == 0:
		cnt += 1
		v //= 3
	while v % 2 == 0:
		cnt -= 1
		v //= 2
	return cnt
n = int(input())
a = list(map(int, input().split()))
a.sort(key=cal, reverse=True)
print(*a)


N = int(input())
L = list(map(int, input().split()))
D = {}
D_2 = {}
check_final = -1
for i in L:
	if D.get(i) is None:
		D[i] = -1
for i in L:
	check = i % 2 == 0
	if check:
		if D.get(i // 2) is not None:
			D[i] = i // 2
			D_2[i // 2] = i
	if D.get(3 * i) is not None:
		D[i] = i * 3
		D_2[3 * i] = i
	if D[i] == -1:
		check_final = i
try:
	kounter = check_final
	print(kounter, end=' ')
	while True:
		print(D_2[kounter], end=' ')
		kounter = D_2[kounter]
except:
	pass


n = int(input())
a = list(map(int, input().split()))
b = {}
for i in range(n):
	x = a[i]
	cell = [0, 0]
	if x % 3 == 0:
		if x // 3 in a:
			cell[0] = 1
	if 2 * x in a:
		cell[1] = 1
	if not cell[0] and (not cell[1]):
		last = x
	b[x] = cell
seq = [last]
while n > 1:
	x = seq[-1]
	n -= 1
	if x & 1:
		seq.append(x * 3)
	else:
		try:
			k = b[x // 2]
			seq.append(x // 2)
		except:
			seq.append(x * 3)
print(*seq[::-1])


import sys
from math import *

def minp():
	return sys.stdin.readline().strip()

def mint():
	return int(minp())

def mints():
	return map(int, minp().split())
n = mint()
a = list(mints())
x = a[0]
r = [x]
while True:
	if x % 3 == 0 and x // 3 in a:
		x //= 3
		r.append(x)
	elif x * 2 in a:
		x *= 2
		r.append(x)
	else:
		break
x = a[0]
l = []
while True:
	if x % 2 == 0 and x // 2 in a:
		x //= 2
		l.append(x)
	elif x * 3 in a:
		x *= 3
		l.append(x)
	else:
		break
print(*l[::-1] + r)


import sys
input = sys.stdin.readline
N = int(input())
S = list(map(int, input().split()))

def neighbours(node, s=S):
	out = [node << 1]
	if node % 3 == 0:
		out.append(node // 3)
	return set((x for x in out if x in s))
G = {}
for x in S:
	G[x] = neighbours(x)

def hamilton(G, size, pt, path=None):
	if path == None:
		path = []
	if pt not in set(path):
		path.append(pt)
		if len(path) == size:
			return path
		for pt_next in G.get(pt, []):
			res_path = [i for i in path]
			candidate = hamilton(G, size, pt_next, res_path)
			if candidate is not None:
				return candidate
for x in S:
	P = hamilton(G, N, x)
	if P:
		print(' '.join(map(str, P)))
		break


from collections import Counter, defaultdict
BS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'

def to_base(s, b):
	res = ''
	while s:
		res += BS[s % b]
		s //= b
	return res[::-1] or '0'
alpha = 'abcdefghijklmnopqrstuvwxyz'
from math import floor, ceil, pi
primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997, 1009, 1013, 1019, 1021, 1031, 1033, 1039, 1049, 1051, 1061, 1063, 1069, 1087, 1091, 1093, 1097, 1103, 1109, 1117, 1123, 1129, 1151, 1153, 1163, 1171, 1181, 1187, 1193, 1201, 1213, 1217, 1223, 1229, 1231, 1237, 1249, 1259, 1277, 1279, 1283, 1289, 1291, 1297, 1301, 1303, 1307, 1319, 1321, 1327, 1361, 1367, 1373, 1381, 1399, 1409, 1423, 1427, 1429, 1433, 1439, 1447, 1451, 1453, 1459, 1471, 1481, 1483, 1487, 1489, 1493, 1499, 1511, 1523, 1531, 1543, 1549, 1553, 1559, 1567, 1571, 1579, 1583, 1597, 1601, 1607, 1609, 1613, 1619, 1621, 1627, 1637, 1657, 1663, 1667, 1669, 1693, 1697, 1699, 1709, 1721, 1723, 1733, 1741, 1747, 1753, 1759, 1777, 1783, 1787, 1789, 1801, 1811, 1823, 1831, 1847, 1861, 1867, 1871, 1873, 1877, 1879, 1889, 1901, 1907, 1913, 1931, 1933, 1949, 1951, 1973, 1979, 1987, 1993, 1997, 1999, 2003, 2011, 2017, 2027, 2029, 2039, 2053, 2063, 2069, 2081, 2083, 2087, 2089, 2099, 2111, 2113, 2129, 2131, 2137, 2141, 2143, 2153, 2161, 2179, 2203, 2207, 2213, 2221, 2237, 2239, 2243, 2251, 2267, 2269, 2273, 2281, 2287, 2293, 2297, 2309, 2311, 2333, 2339, 2341, 2347, 2351, 2357, 2371, 2377, 2381, 2383, 2389, 2393, 2399, 2411, 2417, 2423, 2437, 2441, 2447, 2459, 2467, 2473, 2477, 2503, 2521, 2531, 2539, 2543, 2549, 2551, 2557, 2579, 2591, 2593, 2609, 2617, 2621, 2633, 2647, 2657, 2659, 2663, 2671, 2677, 2683, 2687, 2689, 2693, 2699, 2707, 2711, 2713, 2719, 2729, 2731, 2741, 2749, 2753, 2767, 2777, 2789, 2791, 2797, 2801, 2803, 2819, 2833, 2837, 2843, 2851, 2857, 2861, 2879, 2887, 2897, 2903, 2909, 2917, 2927, 2939, 2953, 2957, 2963, 2969, 2971, 2999, 3001, 3011, 3019, 3023, 3037, 3041, 3049, 3061, 3067, 3079, 3083, 3089, 3109, 3119, 3121, 3137, 3163, 3167, 3169, 3181, 3187, 3191, 3203, 3209, 3217, 3221, 3229, 3251, 3253, 3257, 3259, 3271, 3299, 3301, 3307, 3313, 3319, 3323, 3329, 3331, 3343, 3347, 3359, 3361, 3371, 3373, 3389, 3391, 3407, 3413, 3433, 3449, 3457, 3461, 3463, 3467, 3469, 3491, 3499, 3511, 3517, 3527, 3529, 3533, 3539, 3541, 3547, 3557, 3559, 3571, 3581, 3583, 3593, 3607, 3613, 3617, 3623, 3631, 3637, 3643, 3659, 3671, 3673, 3677, 3691, 3697, 3701, 3709, 3719, 3727, 3733, 3739, 3761, 3767, 3769, 3779, 3793, 3797, 3803, 3821, 3823, 3833, 3847, 3851, 3853, 3863, 3877, 3881, 3889, 3907, 3911, 3917, 3919, 3923, 3929, 3931, 3943, 3947, 3967, 3989, 4001, 4003, 4007, 4013, 4019, 4021, 4027, 4049, 4051, 4057, 4073, 4079, 4091, 4093, 4099, 4111, 4127, 4129, 4133, 4139, 4153, 4157, 4159, 4177, 4201, 4211, 4217, 4219, 4229, 4231, 4241, 4243, 4253, 4259, 4261, 4271, 4273, 4283, 4289, 4297, 4327, 4337, 4339, 4349, 4357, 4363, 4373, 4391, 4397, 4409, 4421, 4423, 4441, 4447, 4451, 4457, 4463, 4481, 4483, 4493, 4507, 4513, 4517, 4519, 4523, 4547, 4549, 4561, 4567, 4583, 4591, 4597, 4603, 4621, 4637, 4639, 4643, 4649, 4651, 4657, 4663, 4673, 4679, 4691, 4703, 4721, 4723, 4729, 4733, 4751, 4759, 4783, 4787, 4789, 4793, 4799, 4801, 4813, 4817, 4831, 4861, 4871, 4877, 4889, 4903, 4909, 4919, 4931, 4933, 4937, 4943, 4951, 4957, 4967, 4969, 4973, 4987, 4993, 4999, 5003, 5009, 5011, 5021, 5023, 5039, 5051, 5059, 5077, 5081, 5087, 5099, 5101, 5107, 5113, 5119, 5147, 5153, 5167, 5171, 5179, 5189, 5197, 5209, 5227, 5231, 5233, 5237, 5261, 5273, 5279, 5281, 5297, 5303, 5309, 5323, 5333, 5347, 5351, 5381, 5387, 5393, 5399, 5407, 5413, 5417, 5419, 5431, 5437, 5441, 5443, 5449, 5471, 5477, 5479, 5483, 5501, 5503, 5507, 5519, 5521, 5527, 5531, 5557, 5563, 5569, 5573, 5581, 5591, 5623, 5639, 5641, 5647, 5651, 5653, 5657, 5659, 5669, 5683, 5689, 5693, 5701, 5711, 5717, 5737, 5741, 5743, 5749, 5779, 5783, 5791, 5801, 5807, 5813, 5821, 5827, 5839, 5843, 5849, 5851, 5857, 5861, 5867, 5869, 5879, 5881, 5897, 5903, 5923, 5927, 5939, 5953, 5981, 5987, 6007, 6011, 6029, 6037, 6043, 6047, 6053, 6067, 6073, 6079, 6089, 6091, 6101, 6113, 6121, 6131, 6133, 6143, 6151, 6163, 6173, 6197, 6199, 6203, 6211, 6217, 6221, 6229, 6247, 6257, 6263, 6269, 6271, 6277, 6287, 6299, 6301, 6311, 6317, 6323, 6329, 6337, 6343, 6353, 6359, 6361, 6367, 6373, 6379, 6389, 6397, 6421, 6427, 6449, 6451, 6469, 6473, 6481, 6491, 6521, 6529, 6547, 6551, 6553, 6563, 6569, 6571, 6577, 6581, 6599, 6607, 6619, 6637, 6653, 6659, 6661, 6673, 6679, 6689, 6691, 6701, 6703, 6709, 6719, 6733, 6737, 6761, 6763, 6779, 6781, 6791, 6793, 6803, 6823, 6827, 6829, 6833, 6841, 6857, 6863, 6869, 6871, 6883, 6899, 6907, 6911, 6917, 6947, 6949, 6959, 6961, 6967, 6971, 6977, 6983, 6991, 6997, 7001, 7013, 7019, 7027, 7039, 7043, 7057, 7069, 7079, 7103, 7109, 7121, 7127, 7129, 7151, 7159, 7177, 7187, 7193, 7207, 7211, 7213, 7219, 7229, 7237, 7243, 7247, 7253, 7283, 7297, 7307, 7309, 7321, 7331, 7333, 7349, 7351, 7369, 7393, 7411, 7417, 7433, 7451, 7457, 7459, 7477, 7481, 7487, 7489, 7499, 7507, 7517, 7523, 7529, 7537, 7541, 7547, 7549, 7559, 7561, 7573, 7577, 7583, 7589, 7591, 7603, 7607, 7621, 7639, 7643, 7649, 7669, 7673, 7681, 7687, 7691, 7699, 7703, 7717, 7723, 7727, 7741, 7753, 7757, 7759, 7789, 7793, 7817, 7823, 7829, 7841, 7853, 7867, 7873, 7877, 7879, 7883, 7901, 7907, 7919]

def primef(n, plst=[]):
	if n == 1:
		return plst
	else:
		for m in primes:
			if n % m == 0:
				return primef(n // m, plst + [m])
		return primef(1, plst + [n])

def lmii():
	return list(map(int, input().split()))

def ii():
	return int(input())

def countOverlapping(string, sub):
	count = start = 0
	while True:
		start = string.find(sub, start) + 1
		if start > 0:
			count += 1
		else:
			return count
n = int(input())
nums = lmii()
c = Counter(nums)
found = False
possible = [([i], c) for i in set(nums)]
while possible:
	(nt, c) = possible.pop(-1)
	if len(nt) == n:
		print(' '.join(list(map(str, nt))))
		found = True
		break
	nen = nt[-1]
	if nen % 3 == 0 and c[nen // 3] > 0:
		cc = c.copy()
		cc[nen // 3] -= 1
		possible.append((nt[:] + [nen // 3], cc))
	elif c[nen * 2] > 0:
		cc = c.copy()
		cc[nen * 2] -= 1
		possible.append((nt[:] + [nen * 2], cc))


n = int(input())
A = [int(x) for x in input().split()]
i = 0
B = A.copy()
C = [1000000000.0]
D = B.copy()
while i < 39:
	while max(D) != 0:
		C = [x // 3 for x in D]
		D = C.copy()
		i = i + 1
	break
k = i - 1
R = set(B.copy())
X = [x for x in list(R) if x % 3 ** k == 0]
L = list({})
A = []
while k >= 0:
	X = [x for x in list(R) if x % 3 ** k == 0]
	X.sort()
	L.extend(X)
	R = R.difference(set(X))
	k = k - 1
print(' '.join([str(x) for x in L]))


def pow3(x):
	c = 0
	while x:
		c += 1
		if x % 3 == 0:
			x = x // 3
		else:
			x = 0
	return -1 * c
N = int(input())
s = [(int(x), pow3(int(x))) for x in input().split()]
s.sort(key=lambda x: (x[1], x[0]))
for i in s:
	print(i[0], end=' ')
print()


seq_len = int(input())
seq = [int(i) for i in input().split()]
head = -1

def arrange_rec(seq):
	head = -1
	if not seq:
		return
	for pot_head in seq:
		if pot_head * 3 not in seq and pot_head % 2 != 0:
			head = pot_head
		elif pot_head * 3 not in seq and pot_head % 2 == 0:
			if pot_head // 2 not in seq:
				head = pot_head
	print(head, end=' ')
	seq.remove(head)
	arrange_rec(seq)
arrange_rec(seq)


n = int(input())
a = [int(x) for x in input().split()]
a.sort()
l1 = [-1] * n
l2 = [-1] * n
for i in range(0, n):
	t = a[i]
	t2 = t * 2
	j = i + 1
	f = False
	while j < n:
		if a[j] > t2:
			break
		if a[j] == t2 and l2[j] == -1:
			f = True
			break
		j += 1
	if f:
		l1[i] = j
		l2[j] = i
	if t % 3 == 0:
		t3 = t // 3
		j = i - 1
		f = False
		while j > -1:
			if a[j] < t3:
				break
			if a[j] == t3 and l2[j] == -1:
				f = True
				break
			j -= 1
		if f:
			l1[i] = j
			l2[j] = i
p = l2.index(-1)
while l1[p] != -1:
	print(a[p], end=' ')
	p = l1[p]
print(a[p])


n = int(input())
inputlist = list(map(int, input().split()))
outputlist = [inputlist.pop(0)]
while len(inputlist) > 0:
	for i in range(len(inputlist)):
		if outputlist[0] * 3 == inputlist[i]:
			outputlist = [inputlist.pop(i)] + outputlist
			break
		elif inputlist[i] * 3 == outputlist[-1]:
			outputlist = outputlist + [inputlist.pop(i)]
			break
		elif outputlist[-1] * 2 == inputlist[i]:
			outputlist = outputlist + [inputlist.pop(i)]
			break
		elif inputlist[i] * 2 == outputlist[0]:
			outputlist = [inputlist.pop(i)] + outputlist
			break
print(' '.join(list(map(str, outputlist))))


n = int(input())
a = [int(i) for i in input().split()]
b = []
for i in range(n):
	for k in a:
		if k * 2 in a or (k // 3 in a and k % 3 == 0):
			pass
		else:
			a.remove(k)
			b.append(k)
print(*reversed(b))


def chooseN(k, arr):
	arr.append(k)
	global nexti, during
	if during[k] == 0:
		return False
	during[k] -= 1
	if len(nexti[k]) == 0:
		if max([during[x] for x in during.keys()]) != 0:
			chooseP(arr[0], list(reversed(arr.copy())))
		else:
			print(' '.join([str(x) for x in arr]))
			during[k] += 1
			return True
	for newk in nexti[k]:
		if chooseN(newk, arr.copy()):
			during[k] += 1
			return True
	during[k] += 1
	return False

def chooseP(k, arr):
	arr.append(k)
	global prev, during
	if during[k] == 0:
		return False
	during[k] -= 1
	if not prev[k]:
		if max([during[x] for x in during.keys()]) != 0:
			during[k] += 1
			return False
		else:
			print(' '.join([str(x) for x in reversed(arr)]))
			during[k] += 1
			return True
	for p in prev[k]:
		if chooseP(p, arr.copy()):
			during[k] += 1
			return True
	during[k] += 1
	return False

def first():
	global prev
	for p in prev:
		if len(prev[p]) == 0:
			return p
	return -1

def any():
	global ls, __c
	__c += 1
	print(ls, __c)
	return ls[__c]
(n, ls, nexti, total, prev, __c) = (int(input()), list(map(int, input().split(' '))), {}, {}, {}, -1)
for i in range(n):
	k = ls[i]
	if k in total:
		total[k] += 1
	else:
		total[k] = 1
		nexti[k] = []
		prev[k] = []
		if k % 3 == 0 and k // 3 in ls:
			nexti[k].append(k // 3)
		if k * 2 in ls:
			nexti[k].append(k * 2)
		if k * 3 in ls:
			prev[k].append(k * 3)
		if k % 2 == 0 and k // 2 in ls:
			prev[k].append(k // 2)
during = total.copy()
start = first()
if start == -1:
	start = any()
while not chooseN(start, []):
	start = any()


n = int(input())
a = list(map(int, input().split()))
res = []
while len(a) > 0:
	el = ''
	for i in range(len(a)):
		el = a[i]
		if len(res) > 0:
			if el == res[-1] * 2 or (res[-1] % 3 == 0 and el == res[-1] // 3):
				res.append(el)
				a.remove(el)
				break
			elif el == res[0] * 3 or (res[0] % 2 == 0 and el == res[0] // 2):
				res = [el] + res
				a.remove(el)
				break
		else:
			res.append(el)
			a.remove(el)
			break
print(*res)


n = int(input())
lst = list(map(int, input().split()))

def conv(x):
	ans = 0
	while x % 2 == 0:
		ans += 1
		x = x // 2
	return (-x, ans)
lst.sort(key=conv)
print(*lst)


def F(num, a_res, a):
	a_new = a[:]
	a_new.remove(num)
	a_res.append(num)
	if num % 3 == 0:
		if num // 3 in a_new:
			a_res = F(num // 3, a_res, a_new)
	if num * 2 in a_new:
		a_res = F(num * 2, a_res, a_new)
	return a_res
n = int(input())
a = [int(i) for i in input().split()]
for i in range(0, n):
	num = a[i]
	a_res = []
	a_res = F(num, a_res, a)
	if len(a_res) == n:
		break
result = ''
for i in a_res:
	result = result + ' ' + str(i)
print(result)


n = int(input())
arr = list(map(int, input().split()))
ans = []
for i in range(n):
	p3 = 0
	t = arr[i]
	while t % 3 == 0:
		t = t // 3
		p3 += 1
	p2 = 0
	t = arr[i]
	while t % 2 == 0:
		t = t // 2
		p2 += 1
	ans.append([p3, -p2, arr[i]])
ans.sort(reverse=True)
for i in ans:
	print(i[2], end=' ')
print('')


from collections import *

def fun(num):
	if num % 3:
		return 0
	else:
		k = num // 3
		return fun(k) + 1
n = int(input())
nums = [int(x) for x in input().split()]
(notgd, good) = ([], [])
Dict = defaultdict(lambda : [])
for num in nums:
	if num % 3:
		notgd.append(num)
	else:
		good.append(num)
notgd.sort()
for num in good:
	k = fun(num)
	Dict[k].append(num)
keys = [x for x in Dict.keys()]
keys.sort(reverse=True)
for key in keys:
	l = Dict[key]
	l.sort()
	for num in l:
		print(num, end=' ')
for num in notgd:
	print(num, end=' ')
print('')


import sys, math
from collections import Counter, deque, defaultdict
mod = 10 ** 9 + 7
INF = float('inf')

def inp():
	return int(sys.stdin.readline())

def inpl():
	return list(map(int, sys.stdin.readline().split()))

def two(x):
	cnt = 0
	while x % 2 == 0:
		cnt += 1
		x //= 2
	return cnt

def thr(x):
	cnt = 0
	while x % 3 == 0:
		cnt += 1
		x //= 3
	return cnt
n = inp()
a = inpl()
b = []
for x in a:
	t2 = two(x)
	t3 = thr(x)
	b.append([x, t2, t3])
b.sort(key=lambda x: x[1])
b.sort(key=lambda x: x[2], reverse=True)
res = []
for (x, z, _) in b:
	res.append(x)
print(*res)


def GetCount3(k):
	count = 0
	while k % 3 == 0:
		k //= 3
		count += 1
	return count
n = input()
l = [(-GetCount3(a), a) for a in map(int, input().split())]
l = [a[1] for a in sorted(l)]
print(*l)


from sys import stdin, stdout

def rearrage_polycarp_math_and_sorting_solution(n: int, sequence):

	def exp(b: int, a: int) -> int:
		k = 0
		while a % b == 0:
			k += 1
			a //= b
		return k
	power_of_3 = [(-exp(3, num), num) for num in sequence]
	power_of_3.sort()
	return [num[1] for num in power_of_3]

def rearrage_polycarp(n: int, sequence):
	polys_seq = set(sequence)
	ordered_seq = [num for num in sequence if not (num % 2 == 0 and num // 2 in polys_seq or 3 * num in polys_seq)]
	n -= 1
	i = 0
	while n:
		if 2 * ordered_seq[i] in polys_seq:
			ordered_seq.append(2 * ordered_seq[i])
		else:
			ordered_seq.append(ordered_seq[i] // 3)
		n -= 1
		i += 1
	return ordered_seq
n = int(stdin.readline().rstrip())
sequence = [int(x) for x in stdin.readline().rstrip().split(' ')]
stdout.write(' '.join((str(num) for num in rearrage_polycarp_math_and_sorting_solution(n, sequence))) + '\n')


f = int(input())
b = input()
c = b.split()
d = []
e = 0
for i in range(f):
	d.append(int(c[i]))
for i in range(f):
	check = 0
	for j in range(f):
		if d[j] == 3 * d[i]:
			check = 1
		if d[i] % 2 == 0 and d[i] == 2 * d[j]:
			check = 1
	if check == 0:
		e = d[i]
print(e, end=' ')
for i in range(f - 1):
	for j in range(f):
		if 3 * d[j] == e:
			e = d[j]
			break
		elif 2 * e == d[j]:
			e = d[j]
			break
	print(e, end=' ')


n = int(input())
a = list(map(int, input().split()))
d = {}
for i in a:
	if i in d:
		d[i] += 1
	else:
		d[i] = 1
mi = min(a)
arr = [mi]
prev = [mi]
while True:
	if 3 * prev[-1] in d and d[3 * prev[-1]] > 0:
		d[3 * prev[-1]] -= 1
		prev.append(3 * prev[-1])
	elif prev[-1] & 1 == 0 and prev[-1] // 2 in d and (d[prev[-1] // 2] > 0):
		d[prev[-1] // 2] -= 1
		prev.append(prev[-1] // 2)
	else:
		break
while True:
	if 2 * arr[-1] in d and d[2 * arr[-1]] > 0:
		d[2 * arr[-1]] -= 1
		arr.append(2 * arr[-1])
	elif arr[-1] % 3 == 0 and arr[-1] // 3 in d and (d[arr[-1] // 3] > 0):
		d[arr[-1] // 3] -= 1
		arr.append(arr[-1] // 3)
	else:
		break
for i in range(len(prev) - 1, 0, -1):
	print(prev[i], end=' ')
print(*arr)


n = int(input())
sequence = input().split()
sequence = [int(x) for x in sequence]
div3_array = [0] * n

def count3(number, idx, div3_array):
	count = 0
	while number % 3 == 0:
		number //= 3
		count += 1
	div3_array[idx] = count
for (idx, number) in enumerate(sequence):
	count3(number, idx, div3_array)
div3_array = list(reversed(sorted(zip(div3_array, sequence))))
div = div3_array[0][0]
start = 0
end = 0
temp_array = []
answer = []
for value in div3_array:
	if value[0] == div:
		end += 1
		temp_array.append(value[1])
		continue
	else:
		temp_array = list(reversed(temp_array))
		answer.extend(temp_array)
		div = value[0]
		temp_array = [value[1]]
temp_array = list(reversed(temp_array))
answer.extend(temp_array)
answer = [str(x) for x in answer]
answer = ' '.join(answer)
print(answer)


import sys
n = int(input())
lis = list(map(int, input().split()))
for j in range(n):
	ans = []
	curr = lis[j]
	cnt = 0
	while cnt < n:
		ans.append(curr)
		cnt += 1
		if curr * 2 in lis:
			curr *= 2
		elif curr // 3 in lis and curr % 3 == 0:
			curr = curr // 3
		else:
			break
	if cnt == n:
		ans = [str(p) for p in ans]
		print(' '.join(ans))
		sys.exit(0)
print(-1)


n = eval(input())
a = input().split()
length = n
start = 0
for i in a:
	if int(i) % 2 == 0:
		if not str(eval(i) * 3) in a and (not str(eval(i) // 2) in a):
			start = eval(i)
			break
	elif not str(eval(i) * 3) in a:
		start = eval(i)
		break
print(start, end=' ')
while length:
	length -= 1
	if start % 2 == 0:
		if start % 3 == 0:
			x = start // 3
			if str(x) in a:
				start = x
				print(start, end=' ')
				continue
		x = start * 2
		if str(x) in a:
			print(x, end=' ')
			start = x
	else:
		x = start * 2
		if str(x) in a:
			print(x, end=' ')
			start = x
			continue
		y = start // 3
		if str(y) in a:
			print(y, end=' ')
			start = y


def key(v):
	r = 0
	while v % 3 == 0:
		v //= 3
		r -= 1
	while v % 2 == 0:
		v //= 2
		r += 1
	return r
input()
print(*sorted(map(int, input().split()), key=key))


n = int(input())
a = [int(x) for x in input().split()]
p = [-1] * n
d = [True] * n
for i in range(n):
	for j in range(n):
		if a[i] * 2 == a[j] or a[i] == a[j] * 3:
			p[j] = i
			d[i] = False
r = [d.index(True)]
while p[r[-1]] >= 0:
	r.append(p[r[-1]])
r.reverse()
print(*(a[x] for x in r))


n = int(input())
a = list(map(int, input().split()))
go = {}
for i in range(n):
	go[i] = []

def add(fr, to):
	global go
	go[fr].append(to)
for (i1, v1) in enumerate(a):
	for (i2, v2) in enumerate(a):
		if v1 * 2 == v2:
			add(i1, i2)
		elif v1 // 3 == v2 and v1 % 3 == 0:
			add(i1, i2)

def find(i, prev_values=None):
	global go
	global a
	if prev_values is None:
		prev_values = [a[i]]
	for v in go[i]:
		prev_values.append(a[v])
		if len(prev_values) == n:
			print(' '.join((str(x) for x in prev_values)))
			quit()
		find(v, prev_values)
		prev_values.pop()
for i in range(n):
	find(i)


n = int(input())
l = [int(i) for i in input().split()]
k = [l[0]]
z = w = l[0]
l.remove(w)
while True:
	if w * 2 in l:
		w = w * 2
		k = k + [int(w)]
		l.remove(w)
	elif w % 3 == 0 and w // 3 in l:
		w = w // 3
		k = k + [w]
		l.remove(w)
	else:
		break
w = z
while True:
	if w % 2 == 0 and w // 2 in l:
		w = w // 2
		k = [w] + k
		l.remove(w)
	elif w * 3 in l:
		w = w * 3
		k = [w] + k
		l.remove(w)
	else:
		break
print(*k)


n = int(input())
a = list(map(int, input().split()))
for i in a:
	q = i + 0
	for j in range(n - 1):
		if i * 2 in a:
			i *= 2
		elif i % 3 == 0 and i // 3 in a:
			i //= 3
		else:
			break
	else:
		print(q, end=' ')
		for j in range(n - 1):
			if q * 2 in a:
				q *= 2
				print(q, end=' ')
			elif q // 3 in a:
				q //= 3
				print(q, end=' ')
		break


(z, zz, dgraphs) = (input, lambda : list(map(int, z().split())), {})
from string import *
from collections import *
from queue import *
from sys import *
from collections import *
from math import *
from heapq import *
from itertools import *
from bisect import *
from collections import Counter as cc
from math import factorial as f

def lcd(xnum1, xnum2):
	return xnum1 * xnum2 // gcd(xnum1, xnum2)

def prime(x):
	p = ceil(x ** 0.5) + 1
	for i in range(2, p):
		if x % i == 0:
			return 0
	return 1

def dfs(u, visit, graph):
	visit[u] = True
	for i in graph[u]:
		if not visit[i]:
			dfs(i, visit, graph)
num = int(z())
l = zz()
for i in sorted(l)[::-1]:
	p = [i]
	for _ in range(num):
		if i % 3 == 0 and i // 3 in l:
			p.append(i // 3)
			i = i // 3
		elif i * 2 in l:
			p.append(i * 2)
			i = i * 2
		else:
			break
	if sorted(p) == sorted(l):
		break
print(*p)


from sys import stdin, stdout

def rint():
	return map(int, stdin.readline().split())

def comp(x):
	i = 0
	tmp = x
	while tmp % 3 == 0:
		tmp //= 3
		i += 1
	n3 = i
	i = 0
	tmp = x
	while tmp % 2 == 0:
		tmp //= 2
		i += 1
	n2 = i
	return -n3 * 100 + n2
n = int(input())
a = list(rint())
a.sort(key=comp)
print(*a)


n = int(input())
pop = list(map(int, input().split()))
lap = []
tam = pop
lok = []
for item in pop:
	lok.append(item)
tod = len(pop)
for item in lok:
	lap.append(item)
	pop.remove(item)
	for x in range(tod):
		if item * 2 in pop:
			lap.append(item * 2)
			pop.remove(item * 2)
			item = item * 2
		elif item % 3 == 0:
			if int(item // 3) in pop:
				lap.append(int(item // 3))
				pop.remove(int(item // 3))
				item = int(item // 3)
			else:
				break
		else:
			break
	if len(lap) == tod:
		print(*lap)
		break
	else:
		lap = []
		pop = []
		for item in lok:
			pop.append(item)


(n, l) = (int(input()), list(map(int, input().split())))
for i in l:
	(a, x) = ([i], l.copy())
	x.remove(i)
	while len(a) != n:
		(p, q) = (a[-1] // 3, a[-1] * 2)
		if a[-1] % 3 == 0 and p in x:
			a.append(p)
			x.remove(p)
		elif q in x:
			a.append(q)
			x.remove(q)
		else:
			break
	if len(a) == n:
		exit(print(*a))


n = int(input())
numbers = input().split()
numbers = [int(x) for x in numbers]
numbers.sort()
numbers.reverse()
temps = []
temp = []

def find_factor(temp, n, numbers):
	if n % 3 == 0 and n // 3 in numbers:
		temp.append(n // 3)
		numbers.remove(n // 3)
		return find_factor(temp, n // 3, numbers)
	else:
		return temp
while len(numbers) != 0:
	flag = numbers[0]
	numbers.remove(flag)
	temp.append(flag)
	temps.append(find_factor(temp, flag, numbers))
	temp = []

def con(temp, temps):
	last = temp[-1]
	for i in temps:
		if i[0] == last * 2:
			temp += i
			temps.remove(i)
			return
	return
i = 0
while len(temps) != 1:
	before = len(temps)
	con(temps[i], temps)
	after = len(temps)
	if before != after:
		continue
	else:
		i += 1
result = temps[0]
result = [str(x) for x in result]
print(' '.join(result))


n = int(input())
a = [int(i) for i in input().split()]
p = []
for i in range(n):
	for j in range(i + 1, n):
		if a[i] == a[j] * 2:
			p.append([a[i], a[j]])
		if a[j] == a[i] * 2:
			p.append([a[j], a[i]])
		if a[i] == a[j] * 3:
			p.append([a[j], a[i]])
		if a[j] == a[i] * 3:
			p.append([a[i], a[j]])
d = dict()
d[p[0][0]] = 0
for j in range(n - 1):
	for i in range(n - 1):
		if d.get(p[i][0]) != None:
			d[p[i][1]] = d[p[i][0]] - 1
		if d.get(p[i][1]) != None:
			d[p[i][0]] = d[p[i][1]] + 1
ans = []
ans_p = []
for (i, j) in d.items():
	ans.append(i)
	ans_p.append(j)
prov = []
for i in range(len(ans_p)):
	prov.append(ans_p[i])
prov.sort()
while ans_p != prov:
	for i in range(n - 1):
		if ans_p[i] > ans_p[i + 1]:
			(ans_p[i], ans_p[i + 1]) = (ans_p[i + 1], ans_p[i])
			(ans[i], ans[i + 1]) = (ans[i + 1], ans[i])
for i in range(len(ans)):
	print(ans[i], end=' ')


def proc(x):
	w = x
	(d2, d3) = (0, 0)
	while x % 2 == 0:
		d2 += 1
		x //= 2
	while x % 3 == 0:
		d3 += 1
		x //= 3
	return ((d2, -d3), w)
n = int(input())
a = list(map(lambda x: proc(int(x)), input().split()))
a.sort()
for i in a:
	print(i[1], end=' ')


n = int(input())
arr = list(map(int, input().split()))
ans = [arr[0]]
front = False
for _ in range(n - 1):
	if not front:
		if ans[-1] * 2 in arr:
			ans.append(ans[-1] * 2)
		elif ans[-1] % 3 == 0 and ans[-1] // 3 in arr:
			ans.append(ans[-1] // 3)
		else:
			front = True
	if front:
		if ans[0] * 3 in arr:
			ans = [ans[0] * 3] + ans
		elif ans[0] % 2 == 0 and ans[0] // 2 in arr:
			ans = [ans[0] // 2] + ans
print(' '.join([str(i) for i in ans]))


n = int(input())
a = list(map(int, input().split()))
b = []
for i in range(n):
	for k in a:
		if not (k * 2 in a or (k // 3 in a and k % 3 == 0)):
			a.remove(k)
			b.append(k)
print(*reversed(b))


import sys
import collections
from collections import Counter, deque
import itertools
import math
import timeit
import random

def sieve(n):
	if n < 2:
		return list()
	prime = [True for _ in range(n + 1)]
	p = 3
	while p * p <= n:
		if prime[p]:
			for i in range(p * 2, n + 1, p):
				prime[i] = False
		p += 2
	r = [2]
	for p in range(3, n + 1, 2):
		if prime[p]:
			r.append(p)
	return r

def divs(n, start=1):
	divisors = []
	for i in range(start, int(math.sqrt(n) + 1)):
		if n % i == 0:
			if n / i == i:
				divisors.append(i)
			else:
				divisors.extend([i, n // i])
	return divisors

def divn(n, primes):
	divs_number = 1
	for i in primes:
		if n == 1:
			return divs_number
		t = 1
		while n % i == 0:
			t += 1
			n //= i
		divs_number *= t

def flin(d, x, default=-1):
	left = right = -1
	for i in range(len(d)):
		if d[i] == x:
			if left == -1:
				left = i
			right = i
	if left == -1:
		return (default, default)
	else:
		return (left, right)

def ceil(n, k):
	return n // k + (n % k != 0)

def ii():
	return int(input())

def mi():
	return map(int, input().split())

def li():
	return list(map(int, input().split()))

def lcm(a, b):
	return abs(a * b) // math.gcd(a, b)

def prr(a, sep=' '):
	print(sep.join(map(str, a)))

def dd():
	return collections.defaultdict(int)

def ddl():
	return collections.defaultdict(list)
n = ii()
d = li()
res = [d[0]]
for i in range(n):
	if not res[i] % 2 and res[i] // 2 in d:
		res.append(res[i] // 2)
	elif res[i] * 3 in d:
		res.append(res[i] * 3)
	else:
		break
res.reverse()
for i in range(len(res) - 1, n):
	if not res[i] % 3 and res[i] // 3 in d:
		res.append(res[i] // 3)
	elif res[i] * 2 in d:
		res.append(res[i] * 2)
print(*res)


def main():
	(n, sequence) = (input(), set(map(int, input().split())))
	firstElement = nThrees = 0
	for element in sequence:
		value = element
		for i in range(39):
			if value % 3:
				if nThrees < i:
					(firstElement, nThrees) = (element, i)
				break
			value //= 3
	if not nThrees:
		return ' '.join(map(str, sorted(sequence)))
	return rearrangeElements(sequence, firstElement)

def rearrangeElements(sequence, firstElement):
	newSequence = ''
	if not firstElement % 2:
		elementBeforeFirst = firstElement // 2
		while elementBeforeFirst in sequence:
			newSequence = f' {elementBeforeFirst}' + newSequence
			elementBeforeFirst //= 2
	while True:
		if firstElement not in sequence:
			return newSequence[1:]
		while firstElement in sequence:
			newSequence += f' {firstElement}'
			firstElement *= 2
		firstElement //= 6
print(main())


from sys import stdin, stdout
from collections import defaultdict, Counter
from bisect import bisect, bisect_left
import math
I = stdin.readline
n = int(I())
arr = [int(x) for x in I().split()]
pre = defaultdict(lambda : 0)
st = 0
for i in arr:
	pre[i] += 1
for i in arr:
	if 3 * i not in pre:
		if i & 1 == 0 and i // 2 not in pre or i & 1 == 1:
			st = i
			break
ans = [0 for i in range(n)]
ans[0] = st
for i in range(1, n):
	if ans[i - 1] * 2 in pre:
		ans[i] = ans[i - 1] * 2
	elif ans[i - 1] % 3 == 0 and ans[i - 1] // 3 in pre:
		ans[i] = ans[i - 1] // 3
for i in range(n):
	print(ans[i], end=' ')
print(' ')


def DFS(n, v):
	global num, pos, ans
	pos[v] = True
	for i in range(n):
		if num[v][i] != 0 and (not pos[i]):
			if len(ans) == 0:
				ans += str(spis[v]) + ' ' + str(spis[i]) + ' '
			else:
				ans += str(spis[i]) + ' '
			DFS(n, i)
n = int(input())
spis = list(map(int, input().split()))
num = [[0 for j in range(n)] for i in range(n)]
pos = [False for i in range(n)]
ans = ''
for i in range(n):
	if spis[i] * 2 in spis:
		num[i][spis.index(spis[i] * 2)] = 1
	if spis[i] % 3 == 0 and spis[i] // 3 in spis:
		num[i][spis.index(spis[i] // 3)] = 1
for i in range(n):
	if False in pos and True in pos:
		pos = [False for j in range(n)]
	if False not in pos:
		break
	ans = ''
	DFS(n, i)
print(ans)


n = int(input())
arr = list(map(int, input().split()))
for (i, x) in enumerate(arr):
	hp = 0
	while not x % 3 ** hp:
		hp += 1
	arr[i] = (hp, x)
arr.sort(key=lambda t: (t[0], -t[1]), reverse=True)
print(*map(lambda o: o[1], arr))


n = int(input())
l = [int(x) for x in input().split()]
for ele in l:
	if ele % 2 == 0:
		if ele // 2 not in l and ele * 3 not in l:
			start = ele
	elif ele * 3 not in l:
		start = ele
while True:
	print(start, end=' ')
	if start * 2 in l:
		start *= 2
		continue
	if start % 3 == 0 and start // 3 in l:
		start = start // 3
		continue
	break


from collections import defaultdict

def cks(v, p):
	s = []
	s.append(v)
	while len(s) > 0:
		c = s.pop()
		if c in p:
			continue
		p.append(c)
		for j in l[c]:
			s.append(j)
	return len(p)
n = int(input())
a = list(map(int, input().split()))
l = defaultdict(list)
for i in range(n):
	k = a[i]
	if a[i] * 2 in a:
		l[a[i]].append(a[i] * 2)
	if a[i] % 3 == 0:
		if a[i] // 3 in a:
			l[a[i]].append(a[i] // 3)
for i in a:
	p = []
	k = cks(i, p)
	if k == n:
		for b in p:
			print(b, end=' ')
		break


def f(n, b, c=0):
	while n % b == 0:
		n //= b
		c += 1
	return c
(n, a) = (int(input()), [int(i) for i in input().split()])
print(*sorted(a, key=lambda x: (f(x, 2), -f(x, 3))))


def f(x, base):
	out = 0
	while x % base == 0:
		x //= base
		out += 1
	return out
n = int(input())
L = list(map(lambda i: [-f(int(i), 3), int(i)], input().split()))
L.sort()
for (i, j) in L:
	print(j, end=' ')
print()


n = int(input())
p = input().rstrip().split(' ')
l = list(p)
for i in range(0, len(p)):
	t = int(p[i])
	del l[i]
	q = []
	q.append(t)
	while 1:
		if len(l) == 0 or len(q) == n:
			break
		elif t % 3 == 0 and str(t // 3) in l:
			t = t // 3
			f = l.index(str(t))
			del l[f]
			q.append(t)
		elif str(t * 2) in l:
			t = t * 2
			f = l.index(str(t))
			del l[f]
			q.append(t)
		else:
			break
	if len(q) == n:
		break
	else:
		l = list(p)
print(*q)


n = int(input())

def foo(p, a):
	if not a:
		return [p]
	for i in a:
		if not p or (p % 3 == 0 and p // 3 == i) or p * 2 == i:
			result = foo(i, a.difference({i}))
			if result is not None:
				return ([p] if p else []) + result
print(*foo(0, set(map(int, input().split()))))


n = int(input())
a = list(map(int, input().split()))
for i in range(n):
	b = a.copy()
	r = []
	r.append(b[i])
	current = b.pop(i)
	while b:
		f = False
		for (j, el) in enumerate(b):
			if current % 3 == 0 and current // 3 == el or current * 2 == el:
				r.append(el)
				current = b.pop(j)
				f = True
				break
		if not f:
			break
	if len(r) == len(a):
		break
print(*r)


n = int(input())
a = [int(x) for x in input().split()]

def fact(x):
	c2 = 0
	c3 = 0
	while x % 2 == 0:
		x = x // 2
		c2 = c2 + 1
	while x % 3 == 0:
		x = x // 3
		c3 = c3 + 1
	return (c2, c3, x)
b = [fact(x) for x in a]
b.sort(key=lambda x: (x[0], -x[1]))
print(' '.join([str(2 ** c2 * 3 ** c3 * k) for (c2, c3, k) in b]))


import sys
n = int(input())
a = list(map(int, input().split()))

def dfs(u):
	r.append(u)
	s.remove(u)
	if len(r) == n:
		print(*r)
		exit(0)
	if u % 3 == 0 and u // 3 in s:
		dfs(u // 3)
	if u * 2 in s:
		dfs(u * 2)
for i in range(n):
	s = set(a)
	r = []
	dfs(a[i])


from collections import Counter, defaultdict, deque
from math import factorial as fact

def primes(n):
	i = 2
	factors = []
	while i * i <= n:
		if n % i:
			i += 1
		else:
			n //= i
			factors.append(i)
	if n > 1:
		factors.append(n)
	return factors

def count3(x):
	c = 0
	while x % 3 == 0:
		x //= 3
		c += 1
	return c

def k(x):
	return count3(x) * 10 ** 19 - x
n = int(input())
a = [int(x) for x in input().split()]
a.sort(key=k, reverse=True)
print(*a)


import sys
n = int(input())
a = list(map(int, input().split()))
(queue, ans) = (0, '')
(d1, d2) = ({}, {})
for i in a:
	d1[i] = 0
for i in a:
	for j in a:
		if j * 3 == i or i * 2 == j:
			d1[j] += 1
			d2[i] = j
for (k, v) in d1.items():
	if v == 0:
		queue = k
for i in range(n - 1):
	ans = ans + str(queue) + ' '
	queue = d2[queue]
ans += str(queue)
print(ans)


I = lambda : list(map(int, input().split()))

def ch(n):
	i = 0
	while not n % 2:
		i += 1
		n //= 2
	return (-n, i)
(n,) = I()
l = I()
l.sort(key=ch)
print(*l)


import time
n = int(input())
a = [int(i) for i in input().split()]
start = time.time()
pdt = []
div = []
for i in range(n):
	pdt.append(a[i] * 2)
	if a[i] % 3 == 0:
		div.append(a[i] // 3)
	else:
		div.append(0)
res = []
for i in range(n):
	c = 0
	for j in range(n):
		if a[i] != pdt[j] and a[i] != div[j]:
			c += 1
	if c == n:
		res.append(a[i])
for elem in res:
	if elem * 2 in a:
		res.append(elem * 2)
	if elem // 3 in a and elem % 3 == 0:
		res.append(elem // 3)
	if len(res) == 100:
		break
for elem in res:
	print(elem, end=' ')


import os
import sys
from math import *
from collections import *
from bisect import *
from io import BytesIO, IOBase

def vsInput():
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def value():
	return tuple(map(int, input().split()))

def array():
	return [int(i) for i in input().split()]

def Int():
	return int(input())

def Str():
	return input()

def arrayS():
	return [i for i in input().split()]

def dfs(graph, start_vertex):
	visited = set()
	traversal = []
	stack = [start_vertex]
	while stack:
		vertex = stack.pop()
		if vertex not in visited:
			visited.add(vertex)
			traversal.append(vertex)
			stack.extend(reversed(graph[vertex]))
	return traversal
n = Int()
a = array()
adj = defaultdict(list)
for i in a:
	if i % 3 == 0 and i // 3 in a:
		adj[i].append(i // 3)
	if i * 2 in a:
		adj[i].append(i * 2)
vis = []
for i in a:
	ans = dfs(adj, i)
	if len(ans) == n:
		print(*ans)
		exit()


n = int(input())
s = list(map(int, input().split()))

def chk(l, r):
	if len(r) == 0:
		print(' '.join(map(str, l)))
		exit()
	ll = l.copy()
	rr = r.copy()
	if l[-1] % 3 == 0 and l[-1] // 3 in rr:
		rr.remove(l[-1] // 3)
		chk(ll + [l[-1] // 3], rr)
	rr = r.copy()
	if l[-1] * 2 in rr:
		rr.remove(l[-1] * 2)
		chk(ll + [l[-1] * 2], rr)
for x in s:
	remain = s.copy()
	remain.remove(x)
	chk([x], remain)


n = int(input())
l = list((int(x) for x in input().split()))
s = set(l)
for j in range(len(l)):
	d = []
	i = l[j]
	while i != -1:
		d.append(i)
		if i % 3 == 0 and i // 3 in s:
			i = l[l.index(i // 3)]
		elif i * 2 in s:
			i = l[l.index(i * 2)]
		else:
			i = -1
	if len(d) == len(l):
		break
for i in d:
	print(i, end=' ')


n = int(input())
a = [int(i) for i in input().split()]
ans = []
ans.append(a[0])
a.remove(a[0])
while len(a) > 0:
	for i in a:
		if i == ans[0] * 3 or (i == ans[0] // 2 and ans[0] % 2 == 0):
			ans = [i] + ans
			a.remove(i)
		if i == ans[-1] * 2 or (i == ans[-1] // 3 and ans[-1] % 3 == 0):
			ans.append(i)
			a.remove(i)
print(*ans)


import operator
n = int(input())
data = list(map(int, input().split(' ')))
p = {}
c = {}
for a in data:
	p[a] = []
	c[a] = []
for a in data:
	if a * 3 in p:
		p[a].append(int(a * 3))
	if a % 2 == 0 and int(a // 2) in p:
		p[a].append(int(a // 2))
	if a % 3 == 0 and int(a // 3) in p:
		c[a].append(int(a // 3))
	if a * 2 in p:
		c[a].append(int(a * 2))
end = [k for (k, v) in c.items() if len(v) == 0]
result = []
result.append(end[0])
t = p[end[0]]
while len(t) != 0:
	result.append(t[0])
	t = p[t[0]]
for i in reversed(result):
	print(i, end=' ')


def dfs(value, count, stop):
	global mySet
	global collect
	global check
	if count == stop:
		return True
	if value % 3 == 0:
		if value // 3 in mySet:
			count += 1
			collect.append(value // 3)
			check = dfs(value // 3, count, stop)
			if not check:
				count -= 1
	if not check:
		if value * 2 in mySet:
			count += 1
			collect.append(value * 2)
			check = dfs(value * 2, count, stop)
			if not check:
				count -= 1
	return check
size = int(input())
collect = []
check = False
mySet = set(map(int, input().split()))
for k in mySet:
	collect.append(k)
	if dfs(k, 1, size):
		break
	else:
		collect = []
print(' '.join((str(i) for i in collect)))


from sys import stdin, stdout
import math
N = int(input())
arr = [int(x) for x in stdin.readline().split()]
fill = [0] * N

def backtrack(arr, idx):
	if idx >= len(arr):
		print(*fill)
		quit()
	if fill[idx - 1] % 3 == 0 and fill[idx - 1] // 3 in arr:
		fill[idx] = fill[idx - 1] // 3
		backtrack(arr, idx + 1)
	elif fill[idx - 1] * 2 in arr:
		fill[idx] = fill[idx - 1] * 2
		backtrack(arr, idx + 1)
	else:
		return 0
for i in range(N):
	start = arr[i]
	fill = [0] * N
	fill[0] = start
	backtrack(arr, 1)


def p3(n):
	res = 0
	while n % 3 == 0:
		n //= 3
		res += 1
	return res

def p2(n):
	res = 0
	while n % 2 == 0:
		n //= 2
		res += 1
	return res

def cmp_to_key(mycmp):

	class K:

		def __init__(self, obj, *args):
			self.obj = obj

		def __lt__(self, other):
			return mycmp(self.obj, other.obj) < 0

		def __gt__(self, other):
			return mycmp(self.obj, other.obj) > 0

		def __eq__(self, other):
			return mycmp(self.obj, other.obj) == 0

		def __le__(self, other):
			return mycmp(self.obj, other.obj) <= 0

		def __ge__(self, other):
			return mycmp(self.obj, other.obj) >= 0

		def __ne__(self, other):
			return mycmp(self.obj, other.obj) != 0
	return K

def comp(x, y):
	return p2(x) - p3(x) - (p2(y) - p3(y))
n = int(input())
arr = list(map(int, input().split()))
arr = sorted(arr, key=cmp_to_key(comp))
s = str(arr[0])
for c in arr[1:]:
	s += f' {c}'
print(s)


n = int(input())
ls = list(map(int, input().split()))
cnt2 = [0] * n
cnt3 = [0] * n
for i in range(n):
	temp = ls[i]
	while temp % 2 == 0:
		temp = temp // 2
		cnt2[i] += 1
	temp = ls[i]
	while temp % 3 == 0:
		temp = temp // 3
		cnt3[i] += 1
for i in range(n):
	for j in range(n - i - 1):
		if cnt2[j] > cnt2[j + 1]:
			(cnt2[j], cnt2[j + 1]) = (cnt2[j + 1], cnt2[j])
			(cnt3[j], cnt3[j + 1]) = (cnt3[j + 1], cnt3[j])
			(ls[j], ls[j + 1]) = (ls[j + 1], ls[j])
for i in range(n):
	for j in range(n - i - 1):
		if cnt3[j] < cnt3[j + 1]:
			(cnt2[j], cnt2[j + 1]) = (cnt2[j + 1], cnt2[j])
			(cnt3[j], cnt3[j + 1]) = (cnt3[j + 1], cnt3[j])
			(ls[j], ls[j + 1]) = (ls[j + 1], ls[j])
for i in ls:
	print(i, end=' ')


from collections import defaultdict
import threading
from sys import stdin, setrecursionlimit
setrecursionlimit(10 ** 6)
input = stdin.readline

def dfs(node, g, comp, vis):
	comp.append(node)
	for i in g[node]:
		if vis[i] == 0 and g[i] != []:
			dfs(i, g, comp, vis)

def main():
	n = int(input())
	ar = list(map(int, input().strip().split()))
	g = defaultdict(list)
	for i in ar:
		if i % 3 == 0:
			g[i].append(i // 3)
		g[i].append(i * 2)
	vis = defaultdict(int)
	for i in sorted(ar, reverse=True):
		if vis[i] == 0:
			comp = []
			dfs(i, g, comp, vis)
			if len(comp) == n:
				print(*comp)
				break
threading.stack_size(10 ** 8)
t = threading.Thread(target=main)
t.start()
t.join()


n = int(input())
u = list(map(int, input().split()))
ok = False

def finl(u, d):
	for i in range(len(u)):
		if u[i] == d:
			return i
	return -1

def gen(i):
	global ans
	if len(ans) == n:
		for i in ans:
			print(i, end=' ')
		exit()
	p = finl(u, u[i] * 2)
	if p != -1:
		ans.append(u[p])
		gen(p)
		ans.pop()
	if u[i] % 3 == 0:
		p = finl(u, u[i] // 3)
		if p != -1:
			ans.append(u[p])
			gen(p)
			ans.pop()
for i in range(n):
	ans = [u[i]]
	gen(i)


from sys import stdin, stdout

def dfs(n):
	global ans
	ans += [n]
	if n in twice:
		dfs(twice[n])
	elif n in div3:
		dfs(div3[n])
for _ in range(1):
	n = int(stdin.readline())
	ans = []
	a = list(map(int, stdin.readline().split()))
	twice = {}
	div3 = {}
	s = set(a)
	ind = {}
	outd = {}
	for v in a:
		if 2 * v in s:
			twice[v] = 2 * v
			ind[2 * v] = ind.get(2 * v, 0) + 1
			outd[v] = outd.get(v, 0) + 1
		if v % 3 == 0 and v // 3 in s:
			div3[v] = v // 3
			ind[v // 3] = ind.get(v // 3, 0) + 1
			outd[v] = outd.get(v, 0) + 1
	for v in a:
		if v not in ind:
			src = v
			break
	dfs(src)
	print(*ans)


import sys
from functools import cmp_to_key
input = sys.stdin.readline

def main():
	n = int(input())
	a = list(map(int, input().split()))

	def threes(x):
		c = 0
		while x % 3 == 0:
			x //= 3
			c += 1
		return c
	a.sort(key=lambda x: (-threes(x), x))
	print(' '.join(map(str, a)))
main()


def binary_search(item, arr):
	left = 0
	right = len(arr) - 1
	while left < right:
		mid = (left + right) // 2
		if arr[mid] == item:
			arr.pop(mid)
			return True
		elif arr[mid] < item:
			left = mid + 1
		elif arr[mid] > item:
			right = mid - 1
	if arr[left] == item:
		arr.pop(left)
		return True
	return

def compute(arr, n):
	temp = [arr[0]]
	arr.pop(0)
	while True:
		if arr:
			if binary_search(temp[0] * 3, arr):
				temp.insert(0, temp[0] * 3)
			elif temp[0] % 2 == 0 and binary_search(temp[0] // 2, arr):
				temp.insert(0, temp[0] // 2)
			else:
				break
		else:
			break
	cur = len(temp)
	n = len(arr)
	for _ in range(n):
		if temp[-1] % 3 == 0:
			temp_1 = binary_search(temp[-1] // 3, arr)
			if temp_1:
				temp.insert(cur, temp[-1] // 3)
			else:
				temp.insert(cur, temp[-1] * 2)
		else:
			temp.insert(cur, temp[-1] * 2)
		cur += 1
	return temp
n = int(input())
arr = list(map(int, input().split()))
arr.sort()
print(*compute(arr, n))


n = int(input())

def f(n):
	r = 0
	while n % 2 == 0:
		n //= 2
		r += 1
	while n % 3 == 0:
		n //= 3
		r -= 1
	return r
print(*sorted(map(int, input().split()), key=f))


import collections
n = int(input())
li3 = set([*map(int, input().split())])
temp = collections.deque()
temp.append(li3.pop())
while li3:
	se = temp[-1]
	if se // 3 in li3:
		temp.append(se // 3)
		li3.remove(se // 3)
	elif se * 2 in li3:
		temp.append(se * 2)
		li3.remove(se * 2)
	else:
		break
while li3:
	se = temp[0]
	if se // 2 in li3:
		temp.appendleft(se // 2)
		li3.remove(se // 2)
	elif se * 3 in li3:
		temp.appendleft(se * 3)
		li3.remove(se * 3)
	else:
		break
print(*temp)


int(input())
a = list(map(int, input().split()))
ra = [a[0]]
a.pop(0)
while len(a):
	f = -1
	ff = -1
	for i in range(len(a)):
		if a[i] * 2 == ra[0]:
			f = i
			ff = 0
			break
		elif ra[-1] * 2 == a[i]:
			f = i
			ff = 1
			break
		elif a[i] % 3 == 0 and a[i] // 3 == ra[0]:
			f = i
			ff = 0
			break
		elif ra[-1] % 3 == 0 and ra[-1] // 3 == a[i]:
			f = i
			ff = 1
			break
	if ff == 0:
		ra = [a[f]] + ra
	else:
		ra = ra + [a[f]]
	a.pop(f)
for i in ra:
	print(i, end=' ')


def comp(d1, d2):
	if d1.first > d2.first:
		return 1
	if d1.first < d2.first:
		return 0
	return bool(d1.second > d2.second)
n = int(input())
a = [int(x) for x in input().split()]
b = []
for x in a:
	tmp = x
	c3 = 0
	c2 = 0
	while x % 3 == 0:
		x //= 3
		c3 += 1
	b.append((-c3, tmp))
b = sorted(b)
for x in b:
	print(x[1], end=' ')


n = int(input())
a = [int(x) for x in input().split()]
a.sort()
ans = []
for i in range(n):
	t = 0
	x = a[i]
	while x % 3 == 0:
		t += 1
		x = x // 3
	ans.append((-t, a[i]))
ans.sort()
for x in ans:
	print(x[1], end=' ')


n = list(map(int, input().strip().split(' ')))
nums = set(map(int, input().strip().split(' ')))
seq = [None]

def check_nums(num):
	global nums
	if num * 3 not in nums:
		if num % 2 == 0:
			if num // 2 in nums:
				return False
			else:
				return True
		else:
			return True
	else:
		return False
for num in list(nums):
	if check_nums(num):
		seq[0] = num
nums.remove(seq[0])
while len(nums) > 1:
	if seq[-1] // 3 in nums:
		seq.append(seq[-1] // 3)
	else:
		seq.append(seq[-1] * 2)
	nums.remove(seq[-1])
seq.append(list(nums)[0])
print(*seq)


from copy import deepcopy
n = int(input())
ns = list(map(int, input().split()))
for x in ns:
	fs = [x]
	js = deepcopy(ns)
	for i in range(n - 1):
		j = fs[-1]
		if not (j % 3 == 0 and j // 3 in js) and (not j * 2 in js):
			break
		elif j % 3 == 0 and j // 3 in js:
			fs.append(j // 3)
			js.remove(j // 3)
		elif j * 2 in js:
			fs.append(j * 2)
			js.remove(j * 2)
	if len(fs) == n:
		print(*fs)
		exit()
print(-1)


import sys
from collections import Counter

def input():
	return sys.stdin.readline().strip()

def list2d(a, b, c):
	return [[c] * b for i in range(a)]

def list3d(a, b, c, d):
	return [[[d] * c for j in range(b)] for i in range(a)]

def list4d(a, b, c, d, e):
	return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]

def ceil(x, y=1):
	return int(-(-x // y))

def INT():
	return int(input())

def MAP():
	return map(int, input().split())

def LIST(N=None):
	return list(MAP()) if N is None else [INT() for i in range(N)]

def Yes():
	print('Yes')

def No():
	print('No')

def YES():
	print('YES')

def NO():
	print('NO')
INF = 10 ** 18
MOD = 10 ** 9 + 7

def rec(a, d):
	if d == N:
		ans.append(a)
		return True
	if a % 3 == 0 and C[a // 3]:
		C[a // 3] -= 1
		if rec(a // 3, d + 1):
			ans.append(a)
			return True
		C[a // 3] += 1
	if C[a * 2]:
		C[a * 2] -= 1
		if rec(a * 2, d + 1):
			ans.append(a)
			return True
		C[a * 2] += 1
	return False
N = INT()
A = LIST()
C = Counter(A)
for (i, a) in enumerate(A):
	ans = []
	if rec(a, 1):
		print(*ans[::-1])
		exit()


def ans():
	N = int(input())
	A = list(map(int, input().split()))
	Ans = []
	for i in range(N):
		a = 0
		b = 0
		c = A[i]
		while A[i] > 0 and c % 3 == 0:
			c = c // 3
			a += 1
		while A[i] > 0 and c % 2 == 0:
			c = c // 2
			b += 1
		Ans += [[a, b]]
		ss = A[i] // (3 ** a * 2 ** b)
	Ans = sorted(Ans)
	f = []
	Ans = Ans[::-1]
	anss = []
	for i in range(1, len(Ans)):
		if Ans[i][0] == Ans[i - 1][0]:
			f += [Ans[i - 1][::-1]]
		else:
			f += [Ans[i - 1][::-1]]
			f = sorted(f)
			for k in range(len(f)):
				f[k] = f[k][::-1]
			anss += f
			f = []
	if Ans[len(Ans) - 1] != Ans[len(Ans) - 2]:
		f += [Ans[i][::-1]]
		f = sorted(f)
		for k in range(len(f)):
			f[k] = f[k][::-1]
		anss += f
	for k in range(len(anss)):
		if k != len(anss) - 1:
			print(ss * 3 ** anss[k][0] * 2 ** anss[k][1], end=' ')
		else:
			print(ss * 3 ** anss[k][0] * 2 ** anss[k][1])
ans()


n = int(input())
l = list(map(int, input().split()))

def conv(n):
	i = 0
	while n % 2 == 0:
		i += 1
		n /= 2
	return (-n, i)
l.sort(key=conv)
print(*l)


n = int(input())
arr = list(map(int, input().split()))
arr1 = []
for i in range(n):
	if arr[i] % 3 == 0:
		if arr[i] // 3 in arr:
			arr1.append([arr[i], arr[i] // 3])
	if arr[i] * 2 in arr:
		arr1.append([arr[i], arr[i] * 2])
arr1 = sorted(arr1)
ans = [arr1[0][0], arr1[0][1]]
x = arr1[0][0]
y = arr1[0][1]
while len(ans) != n:
	for i in range(1, len(arr1)):
		if arr1[i][0] == y:
			y = arr1[i][1]
			ans.append(arr1[i][1])
		elif arr1[i][1] == x:
			x = arr1[i][0]
			ans.insert(0, arr1[i][0])
print(*ans)


n = int(input())
a = list(map(int, input().split()))
l = [a[0]]
for i in range(1, n):
	for j in range(i, n):
		if l[-1] * 2 == a[j]:
			l += [a[j]]
			(a[i], a[j]) = (a[j], a[i])
			break
		if l[-1] // 3 == a[j] and l[-1] % 3 == 0:
			l += [a[j]]
			(a[i], a[j]) = (a[j], a[i])
			break
		if l[0] * 3 == a[j]:
			l = [a[j]] + l
			(a[i], a[j]) = (a[j], a[i])
			break
		if l[0] // 2 == a[j] and l[0] % 2 == 0:
			l = [a[j]] + l
			(a[i], a[j]) = (a[j], a[i])
			break
print(*l)


def canTake(nbr, lst, dict):
	return dict[nbr] != lst.count(nbr)

def exists(nbr, dict):
	return nbr in dict

def dfs(nbr, lst, dict, n):
	if len(lst) == n:
		print(*lst)
		exit(0)
	possibilities = []
	if exists(nbr * 2, dict) and canTake(nbr * 2, lst, dict):
		possibilities.append(nbr * 2)
	if nbr % 3 == 0 and exists(nbr // 3, dict) and canTake(nbr // 3, lst, dict):
		possibilities.append(nbr // 3)
	if len(possibilities) == 0:
		return []
	for item in possibilities:
		lst.append(item)
		dfs(item, lst, dict, n)

def main():
	n = int(input())
	arr = map(int, input().split())
	dict = {}
	for item in arr:
		if exists(item, dict):
			dict[item] += 1
		else:
			dict[item] = 1
	for item in dict:
		dfs(item, [item], dict, n)
main()


def GetCount3(k):
	count = 0
	while k % 3 == 0:
		k //= 3
		count += 1
	return count
n = input()
l = sorted(map(int, input().split()), key=lambda a: (-GetCount3(a), a))
print(*l)


from sys import stdin

def solve(el, input):
	if el not in input:
		return []
	res1 = solve(el * 2, input)
	res2 = solve(el // 3, input) if el % 3 == 0 else []
	res = max([res1, res2], key=len)
	return [el] + res

def threetwo(n, input):
	for el in input:
		result = solve(el, input)
		if len(result) == n:
			return result
n = int(stdin.readline())
input = [int(el) for el in stdin.readline().split()]
result = threetwo(n, set(input))
print(' '.join((str(i) for i in result)))


n = int(input())
arr = list(map(int, input().split()))
ans = [arr[0]]
stack = [arr[0]]
visited = set()
while stack:
	p = stack.pop()
	visited.add(p)
	if p * 2 in arr and p * 2 not in visited:
		ans.append(p * 2)
		stack.append(p * 2)
	if p % 3 == 0 and p // 3 in arr and (p // 3 not in visited):
		ans.append(p // 3)
		stack.append(p // 3)
	if p * 3 in arr and p * 3 not in visited:
		ans.insert(0, p * 3)
		stack.append(p * 3)
	if p % 2 == 0 and p // 2 in arr and (p // 2 not in visited):
		ans.insert(0, p // 2)
		stack.append(p // 2)
print(*ans)


n = int(input())
a = list(map(int, input().split()))
forward = [None] * n
backward = [None] * n
for i in range(n):
	for j in range(n):
		if 3 * a[i] == a[j] or a[i] == 2 * a[j]:
			backward[i] = j
			forward[j] = i
			break
head = backward.index(None)
while head is not None:
	print(a[head], end=' ')
	head = forward[head]


import sys
import math
import collections
import bisect

def get_ints():
	return map(int, sys.stdin.readline().strip().split())

def get_list():
	return list(map(int, sys.stdin.readline().strip().split()))

def get_string():
	return sys.stdin.readline().strip()
for t in range(1):
	n = int(input())
	arr = get_list()
	for i in range(n):
		start = arr[i]
		ans = [start]
		dup = arr.copy()
		dup.remove(start)
		pos = 0
		while len(ans) < n:
			prev = ans[pos]
			if prev * 2 in dup:
				ans.append(prev * 2)
				dup.remove(prev * 2)
			elif prev % 3 == 0:
				if prev // 3 in dup:
					ans.append(prev // 3)
					dup.remove(prev // 3)
				else:
					break
			else:
				break
			pos += 1
		if len(ans) == n:
			print(*ans)
			break


def dfs(n, dic, a, right, left):
	dic[n] = 1
	for i in a:
		if dic[i] == 0:
			if i * 3 == n or n * 2 == i:
				left.append(i)
				dfs(i, dic, a, right, left)
			if n * 3 == i or i * 2 == n:
				right.append(i)
				dfs(i, dic, a, right, left)
	return (right, left)

def main():
	n = int(input())
	b = [0] * n
	a = [0] * n
	left = [0] * 0
	right = [0] * 0
	a = [int(_) for _ in input().split()]
	dic = dict(zip(a, b))
	(right, left) = dfs(max(a), dic, a, right, left)
	right.reverse()
	ans = right + [max(a)] + left
	print(*ans, sep=' ')
main()


n = int(input())
a = [int(item) for item in input().split()]

def solve(start, occ, d):
	if d == n - 1:
		return True
	u = False
	v = False
	if start % 3 == 0 and start // 3 in occ and (occ[start // 3] != 0):
		new_occ = dict(occ)
		new_occ[start // 3] = 0
		u = solve(start // 3, new_occ, d + 1)
	if start * 2 in occ and occ[start * 2] != 0:
		new_occ = dict(occ)
		new_occ[start * 2] = 0
		v = solve(start * 2, new_occ, d + 1)
	return u or v

def solve2(start, occ, d):
	if d == n - 1:
		return (True, [start])
	u = (False, [])
	v = (False, [])
	if start % 3 == 0 and start // 3 in occ and (occ[start // 3] != 0):
		new_occ = dict(occ)
		new_occ[start // 3] = 0
		u = solve2(start // 3, new_occ, d + 1)
	if start * 2 in occ and occ[start * 2] != 0:
		new_occ = dict(occ)
		new_occ[start * 2] = 0
		v = solve2(start * 2, new_occ, d + 1)
	if u[0]:
		return (True, [start] + u[1])
	if v[0]:
		return (True, [start] + v[1])
	return (False, [])
occ = {key: 0 for key in a}
for i in range(n):
	occ[a[i]] += 1
for i in range(n):
	new_occ = dict(occ)
	new_occ[a[i]] -= 1
	if solve(a[i], new_occ, 0):
		new_occ = dict(occ)
		new_occ[a[i]] -= 1
		print(' '.join((str(item) for item in solve2(a[i], new_occ, 0)[1])))
		break


from bisect import *
n = int(input())
nbs = list(map(int, input().split()))
nbs.sort()
res_ = None

def recursion(n, available, res):
	global res_
	if res_ != None:
		return
	possible = set()
	if len(available) == 0:
		res_ = res
	if n % 3 == 0:
		i3 = bisect_left(available, n // 3)
		if i3 != len(available) and available[i3] == n // 3:
			possible.add(i3)
	i2 = bisect_left(available, n * 2)
	if i2 != len(available) and available[i2] == n * 2:
		possible.add(i2)
	for p in possible:
		a_ = available.copy()
		del a_[p]
		recursion(available[p], a_, res + [available[p]])
for i in range(n):
	a = nbs.copy()
	del a[i]
	recursion(nbs[i], a, [nbs[i]])
s = ''
for n in res_:
	s += str(n) + ' '
print(s[:-1])


def three_num(n):
	result = 0
	while n % 3 == 0:
		n //= 3
		result += 1
	return result
n = int(input())
x = list(map(int, input().split()))
y = set(x)
first = x[0]
max_num = three_num(x[0])
for i in range(1, n):
	temp = three_num(x[i])
	if temp > max_num:
		max_num = temp
		first = x[i]
	elif temp == max_num and first > x[i]:
		first = x[i]
res = []
res.append(first)
y.remove(first)
for i in range(n - 1):
	if res[i] * 2 in y:
		y.remove(res[i] * 2)
		res.append(res[i] * 2)
	else:
		y.remove(res[i] // 3)
		res.append(res[i] // 3)
print(' '.join(map(str, res)))


import math
import sys
import itertools
import itertools
import collections

def sa(Type=int):
	return [Type(x) for x in input().split()]

def countFactors(n, factor):
	if n % factor != 0:
		return 0
	cc = 1
	product = factor
	while True:
		product *= factor
		if product > n:
			break
		if n % product == 0:
			cc += 1
	return cc

def solve(t):
	n = int(input())
	arr = sa()
	arr = [(x, countFactors(x, 3)) for x in arr]
	arr.sort(key=lambda x: (x[1], -x[0]), reverse=True)
	print(' '.join(map(lambda x: str(x[0]), arr)))
solve(1)


(n, x, t) = (int(input()), sorted(list(map(int, input().split()))), [])
t.append(x[0])
for j in t:
	if 2 * j in x:
		t.append(x.pop(x.index(2 * j)))
	elif j // 3 in x and j % 3 == 0:
		t.append(x.pop(x.index(j // 3)))
while len(t) < n:
	if t[0] * 3 in x:
		t.insert(0, x.pop(x.index(t[0] * 3)))
	elif t[0] // 2 in x:
		t.insert(0, x.pop(x.index(t[0] // 2)))
print(' '.join(map(str, t)))


from bisect import bisect
from collections import defaultdict
from math import gcd, sqrt, ceil, inf
from collections import Counter
import sys
sys.setrecursionlimit(10 ** 9)
n = int(input())
l = list(map(int, input().split()))
hash = defaultdict(int)
for i in l:
	hash[i] += 1
for i in range(n):
	start = l[i]
	yo = [start]
	for i in l:
		hash[i] += 1
	hash[start] -= 1
	for j in range(n - 1):
		if start % 3 == 0 and hash[start // 3] != 0:
			hash[start // 3] -= 1
			start = start // 3
			yo.append(start)
		elif hash[start * 2] != 0:
			hash[start * 2] -= 1
			start = start * 2
			yo.append(start)
		else:
			break
	if len(yo) == n:
		print(*yo)
		exit()


def check(e, u):
	if not len(u):
		return 0
	elif e % 3 == 0 and e // 3 in u:
		t = u.copy()
		t.remove(e // 3)
		o = check(e // 3, t)
		if o == -1:
			if e * 2 in u:
				t = u.copy()
				t.remove(e * 2)
				o = check(e * 2, t)
				if o == -1:
					return -1
				elif o == 0:
					return [e * 2]
				else:
					return [e * 2] + o
			else:
				return -1
		elif o == 0:
			return [e // 3]
		else:
			return [e // 3] + o
	elif e * 2 in u:
		t = u.copy()
		t.remove(e * 2)
		o = check(e * 2, t)
		if o == -1:
			return -1
		elif o == 0:
			return [e * 2]
		else:
			return [e * 2] + o
	else:
		return -1
n = int(input())
l = list(map(int, input().split()))
for e in l:
	t = l.copy()
	t.remove(e)
	o = check(e, t)
	if o == -1:
		continue
	print(e, *o)
	break


def step3(p):
	kp = 0
	while p % 3 == 0:
		kp += 1
		p //= 3
	return kp
n = input()
L = [(-step3(x), x) for x in map(int, input().split())]
L = [x[1] for x in sorted(L)]
print(*L)


from collections import deque

class Node:

	def __init__(self, val):
		self.val = val
		self.child = []

class Graph:

	def __init__(self, size):
		self.node = {i: Node(i) for i in size}
		self.edge = {i: 0 for i in size}

	def insert(self, val1):
		if val1 * 2 in self.node:
			self.node[val1].child.append(self.node[2 * val1])
			self.edge[2 * val1] += 1
		elif val1 % 3 == 0 and val1 // 3 in self.node:
			self.node[val1].child.append(self.node[val1 // 3])
			self.edge[val1 // 3] += 1

	def dfs(self):
		visited = {i: False for i in self.node}
		dfs_node = 1
		for i in self.edge:
			if self.edge[i] == 0:
				dfs_node = self.node[i]
				break
		ans = []
		stack = deque()
		stack.append(dfs_node)
		ans.append(dfs_node.val)
		visited[dfs_node.val] = True
		while len(stack) != 0:
			curr = stack.pop()
			for i in curr.child:
				if not visited[i.val]:
					visited[i.val] = True
					stack.append(i)
					ans.append(i.val)
		return ans

	def pr(self):
		for i in self.node:
			print(i.val)
			print(i.child)
b = int(input())
a = input().split()
a = [int(i) for i in a]
g = Graph(a)
for i in a:
	g.insert(i)
p = g.dfs()
p = [str(i) for i in p]
print(' '.join(p))


n = int(input())
l = list(map(int, input().split()))
m = []
for i in range(n):
	flag = 1
	x = l[i]
	for j in range(n):
		if x == 2 * l[j] or x * 3 == l[j]:
			flag = 0
			break
		else:
			continue
	if flag == 1:
		m.append(x)
for i in range(n):
	for j in range(n):
		if l[j] * 3 == m[i] or l[j] == m[i] * 2:
			m.append(l[j])
			break
for i in range(n):
	print(m[i], end=' ')
print()


def deg_3(x):
	deg = 0
	while x % 3 == 0:
		x //= 3
		deg += 1
	return deg
n = int(input())
a = map(int, input().split())
a_deg = sorted([(a_i, deg_3(a_i)) for a_i in a], key=lambda x: (-x[1], x[0]))
print(' '.join([str(val) for (val, deg) in a_deg]))


import sys
n = int(input())
a = [*map(int, input().split())]

def solve(c, r, s, x):
	sys.setrecursionlimit(sys.getrecursionlimit() + 1)
	r.remove(x)
	s.remove(x)
	c.append(x)
	if len(r) == 0:
		print(*c)
		exit()
	if x % 3 == 0 and x // 3 in s:
		solve([*c], [*r], set([*s]), x // 3)
	if x * 2 in s:
		solve([*c], [*r], set([*s]), x * 2)
	return
for i in a:
	solve([], [*a], set(a), i)


n = int(input())
li = list(map(int, input().split()))
g = {}

def dfs(e, v, order):
	if e not in v:
		v[e] = 1
		if e % 3 == 0:
			if e // 3 in g:
				order.append(e // 3)
				dfs(e // 3, v, order)
		if e * 2 in g:
			order.append(e * 2)
			dfs(e * 2, v, order)
for i in li:
	g[i] = 0
for i in li:
	vis = {}
	Aorder = []
	Aorder.append(i)
	dfs(i, vis, Aorder)
	if len(Aorder) == n:
		print(*Aorder)
		break


def found_sequence(possible_sequence, lookup):
	if len(possible_sequence) == n:
		print(' '.join(list(map(str, possible_sequence))))
		return True
	else:
		last_element = possible_sequence[-1]
		if last_element % 3 == 0 and last_element // 3 in lookup and (lookup[last_element // 3] >= 1):
			lookup[last_element // 3] -= 1
			possible_sequence.append(last_element // 3)
			if found_sequence(possible_sequence, lookup):
				return True
		if last_element * 2 in lookup and lookup[last_element * 2] >= 1:
			lookup[last_element * 2] -= 1
			possible_sequence.append(last_element * 2)
			if found_sequence(possible_sequence, lookup):
				return True
		return False
n = int(input())
given_sequence = list(map(int, input().split()))
lookup = {}
result = []
for element in given_sequence:
	if element in lookup:
		lookup[element] += 1
	else:
		lookup[element] = 1
for index in range(len(given_sequence)):
	if found_sequence([given_sequence[index]], dict(lookup)):
		break


import sys
n = int(sys.stdin.readline())
nums = list(map(int, sys.stdin.readline().split()))
edges = {}
for i in nums:
	for j in nums:
		if i * 2 == j:
			if i in edges:
				edges[i].append(j)
			else:
				edges[i] = [j]
		if j * 3 == i:
			if i in edges:
				edges[i].append(j)
			else:
				edges[i] = [j]
inin = {}
for i in nums:
	inin[i] = 0
for i in edges:
	for j in edges[i]:
		inin[j] += 1
ans = []
queue = []
for i in nums:
	if inin[i] == 0:
		queue.append(i)
while len(queue) > 0:
	v = queue.pop()
	ans.append(v)
	if v in edges:
		for i in edges[v]:
			inin[i] -= 1
			if inin[i] == 0:
				queue.append(i)
for i in ans:
	print(i, end=' ')


n = int(input())
a = list(map(int, input().split()))

def count3(n):
	ret = 0
	while n % 3 == 0:
		ret += 1
		n = n // 3
	return ret
v = [[0, 0] for i in range(n)]
for i in range(len(a)):
	v[i][1] = a[i]
	v[i][0] = -count3(v[i][1])
v.sort()
for i in v:
	print(i[1], end=' ')


v = lambda p: lambda n: 0 if n % p else 1 + v(p)(n // p)
input()
print(' '.join(map(str, sorted(reversed(sorted(map(int, input().split()), key=v(3))), key=v(2)))))


import sys
n = int(sys.stdin.readline().rstrip('\n'))
ls = list(map(int, sys.stdin.readline().split()))
res = []
for i in range(n):
	for l in ls:
		if l * 2 in ls or (l % 3 == 0 and l // 3 in ls):
			continue
		else:
			res.append(l)
			ls.remove(l)
res = list(map(str, res[::-1]))
p = ' '.join(res)
print(p)


import traceback
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
import math
from collections import defaultdict as dfd, Counter
from functools import lru_cache
from itertools import accumulate

def geti():
	return int(input())

def gets():
	return input()

def getil():
	return list(map(int, input().split()))

def getsl():
	return input().split()

def getinps(s):
	inps = s.split()
	m = {'i': geti, 's': gets, 'il': getil, 'sl': getsl}
	if len(inps) == 1:
		return m[s]()
	return [m[k]() for k in inps]

def get2d(nrows, ncols, n=0):
	return [[n] * ncols for r in range(nrows)]

def get_acc(a):
	return list(accumulate(a))

def get_ncr(n, r):
	if n < r:
		return 0
	return math.factorial(n) // (math.factorial(r) * math.factorial(n - r))

def get_nc2(n):
	return n * (n - 1) // 2

def get_npr(n, r):
	if n < r:
		return 0
	return math.factorial(n) // math.factorial(r)
inf = float('inf')
mod = 10 ** 9 + 7

def main():
	(N, a) = getinps('i il')
	(par, ch) = ({}, {})
	u = set(a)
	for i in a:
		if i * 2 in u:
			z = i * 2
		elif i % 3 == 0 and i // 3 in u:
			z = i // 3
		else:
			continue
		par[z] = i
		ch[i] = z
	r = [i for i in u if i not in par][0]
	h = []
	while r in ch:
		h.append(r)
		r = ch[r]
	h.append(r)
	return h
try:
	ans = main()
	print(*ans)
except Exception as e:
	print(e)
	traceback.print_exc()


n = int(input())
a = list(map(int, input().split()))
num = {}
for i in range(50):
	num[i] = []
for i in range(n):
	temp = a[i]
	cnt = 0
	while True:
		if temp % 3 == 0:
			cnt += 1
			temp //= 3
		else:
			break
	num[cnt].append(a[i])
ans = []
for i in range(50)[::-1]:
	temp = num[i]
	temp = sorted(temp)
	for i in temp:
		ans.append(i)
print(*ans, sep=' ')


n = int(input())
l = list(map(int, input().split()))
d = []
for i in l:
	d.clear()
	t = l[:]
	t.remove(i)
	d.append([[i], t])
	for k in range(n - 1):
		to_del = []
		for p in range(len(d)):
			num = d[p][0][-1]
			s = d[p][1]
			in_mod = bool(num % 3 == 0)
			in_t = False
			if in_mod:
				in_t = bool(num // 3 in s)
			in_d = bool(num * 2 in s)
			if in_t and in_d:
				d.append([[s * 2], s.remove(num * 2)])
				d[p][0].append(num // 3)
				d[p][1].remove(num // 3)
			elif in_t:
				d[p][0].append(num // 3)
				d[p][1].remove(num // 3)
			elif in_d:
				d[p][0].append(num * 2)
				d[p][1].remove(num * 2)
			else:
				to_del.append(p)
		a = 0
		for o in sorted(to_del):
			d.pop(o - a)
			a += 1
		if d == []:
			break
	if d != []:
		print(' '.join(map(str, d[0][0])))
		exit()


n = int(input())
s = list(map(int, input().split()))
result = []
i = 0

def checkeven(a):
	if a % 2 == 0:
		return True
	else:
		return False

def check(a):
	b = 0
	if checkeven(a) is True:
		if a // 2 in s:
			b += 1
		if a * 2 in s:
			b += 10
		if a * 3 in s:
			b += 1
		if a / 3 in s:
			b += 10
	elif checkeven(a) is False:
		if a / 2 in s:
			b += 1
		if a * 2 in s:
			b += 10
		if a * 3 in s:
			b += 1
		if a // 3 in s:
			b += 10
	if b == 10 or b == 0:
		return True
while i < n and n != 0:
	if check(s[i]) is True:
		result.append(s[i])
		s.remove(s[i])
		i = 0
		n -= 1
	else:
		i += 1
for k in range(len(result)):
	print(result[k], end=' ')


n = int(input())
arr = list(map(int, input().split()))
minVal = min(arr)
currentVal = minVal
index = arr.index(currentVal)
answer = []
while True:
	answer.append(currentVal)
	arr[index] = -1
	if currentVal % 3 == 0 and currentVal // 3 in arr:
		currentVal = currentVal // 3
	elif currentVal * 2 in arr:
		currentVal *= 2
	else:
		break
	index = arr.index(currentVal)
if len(answer) < n:
	currentVal = minVal
	answer2 = []
	while True:
		if currentVal * 3 in arr:
			currentVal = currentVal * 3
			answer2.append(currentVal)
		elif currentVal % 2 == 0 and currentVal // 2 in arr:
			currentVal //= 2
			answer2.append(currentVal)
		else:
			break
		index = arr.index(currentVal)
		arr[index] = -1
	answer2.reverse()
	answer = answer2 + answer
print(*answer)


from collections import defaultdict
n = int(input())
a = list(map(int, input().split()))
d = defaultdict(list)
for ai in a:
	tmp = ai
	cnt = 0
	while tmp % 3 == 0:
		tmp //= 3
		cnt += 1
	d[cnt].append(ai)
for k in d.keys():
	d[k].sort()
keys = list(d.keys())
keys.sort(reverse=True)
ans = []
for k in keys:
	ans += d[k]
print(*ans)


def dfs(u):
	ans.append(u)
	for v in graph[u]:
		dfs(v)
from collections import defaultdict
R = lambda : list(map(int, input().split()))
n = int(input())
arr = R()
freq = {}
graph = defaultdict(list)
ind = {}
for i in arr:
	ind[i] = 0
	freq[i] = freq.get(i, 0) + 1
for i in freq:
	while freq[i] > 0:
		ok = False
		if i * 2 in freq:
			ok = True
			freq[i] -= 1
			graph[i].append(i * 2)
			ind[i * 2] += 1
		elif i % 3 == 0 and i // 3 in freq:
			ok = True
			freq[i] -= 1
			graph[i].append(i // 3)
			ind[i // 3] += 1
		if not ok:
			break
st = -1
for i in ind:
	if ind[i] == 0:
		st = i
		break
ans = []
dfs(st)
print(' '.join(map(str, ans)))


n = int(input())
flag = 0
lst = [int(x) for x in input().split()]
for i in lst:
	if i * 2 not in lst and i // 3 not in lst:
		val = i
		flag = 1
if flag == 0:
	val = 4
s = []
s.append(val)
top = 0
lst.remove(val)
loop = len(lst)
while loop != 0:
	a = s[top] // 2
	b = s[top] * 3
	if a in lst:
		s.append(a)
		lst.remove(a)
	elif b in lst:
		s.append(b)
		lst.remove(b)
	top = top + 1
	loop = loop - 1
loop = len(s)
while loop != 0:
	print(s.pop(), end=' ')
	loop = loop - 1


import math
n = int(input())
lst = list(map(int, input().split()))
dic = {}
for e in lst:
	if e * 2 in lst:
		dic[e] = e * 2
	elif math.floor(e / 3) == math.ceil(e / 3) and e // 3 in lst:
		dic[e] = e // 3
	else:
		dic[e] = -1
dic_val = dic.values()
start = -1
ans = []
for i in range(n):
	if lst[i] in dic_val:
		pass
	else:
		start = lst[i]
		break
while start != -1:
	ans.append(start)
	start = dic[start]
print(*ans)


n = int(input())
a = list(map(int, input().split()))
check = set(a)
start = 0
for x in a:
	if x * 3 not in check and (x % 2 == 1 or x // 2 not in check):
		start = x
		break
ans = [start]
cnt = 1
while cnt < n:
	if start % 3 == 0 and start // 3 in check:
		ans.append(start // 3)
		start = start // 3
	else:
		ans.append(2 * start)
		start = 2 * start
	cnt += 1
print(*ans)


n = int(input())
a = list(map(int, input().split()))

def func(x):
	b = list(a)
	r = []
	for i in range(n):
		if x % 3 == 0 and x // 3 in b:
			x //= 3
			b.remove(x)
			r += [x]
		if x * 2 in b:
			x *= 2
			b.remove(x)
			r += [x]
	return r
for i in a:
	if sorted([i] + func(i)) == sorted(a):
		print(' '.join(map(str, [i] + func(i))))


n = int(input())
vv = list(map(int, input().split()))
arr = [[0, 0] for _ in range(n)]
for i in range(n):
	cur = vv[i]
	while cur % 2 == 0:
		cur //= 2
		arr[i][0] += 1
	while cur % 3 == 0:
		cur //= 3
		arr[i][1] += 1
gr = [[] for _ in range(n)]
for i in range(n):
	for j in range(n):
		if arr[j][0] - arr[i][0] == 1 and arr[i][1] - arr[j][1] == 0:
			gr[i].append(j)
		if arr[j][0] - arr[i][0] == 0 and arr[i][1] - arr[j][1] == 1:
			gr[i].append(j)

def dfs(v):
	ans.append(vv[v])
	used[v] = True
	for u in gr[v]:
		dfs(u)
for i in range(n):
	ans = []
	used = [False for _ in range(n)]
	dfs(i)
	if len(ans) == n:
		print(*ans)


from collections import deque
n = int(input())
a = list(map(int, input().split()))
ans = deque([a[0]])
prev = a[0]
a.remove(prev)
while len(ans) != n:
	num = prev
	prevone = 0
	prevtwo = 0
	nextone = 0
	nexttwo = 0
	if num % 3 == 0:
		nextone = num / 3
		nexttwo = num * 2
	else:
		nextone = -1
		nexttwo = num * 2
	if num % 2 == 0:
		prevone = num / 2
		prevtwo = num * 3
	else:
		prevone = -1
		prevtwo = num * 3
	if nextone in a:
		ans.append(int(nextone))
		a.remove(nextone)
		prev = nextone
	elif nexttwo in a:
		ans.append(int(nexttwo))
		a.remove(nexttwo)
		prev = nexttwo
	elif prevone in a:
		ans.appendleft(int(prevone))
		a.remove(prevone)
		prev = prevone
	elif prevtwo in a:
		ans.appendleft(int(prevtwo))
		a.remove(prevtwo)
		prev = prevtwo
	elif len(ans) != 1:
		prev = ans[0]
	else:
		prev = a[0]
		a.append(ans[0])
		ans = deque([a[0]])
		a.remove(prev)
for i in ans:
	print(i, end=' ')


from operator import itemgetter

def spec(num, num2):
	i = 0
	while num >= num2:
		if num % num2 != 0:
			return i
		num //= num2
		i += 1
	return i
n = int(input())
ai = list(map(int, input().split()))
ai3 = [[0.0] * 2 for i in range(n)]
for i in range(n):
	ai3[i][0] = i
	ai3[i][1] = spec(ai[i], 3) - spec(ai[i], 2) * 0.0001
ai3 = sorted(ai3, key=itemgetter(1))
for i in range(n - 1, -1, -1):
	print(ai[ai3[i][0]], end=' ')


n = int(input())
li = list(map(int, input().split()))
l = []
for i in range(40):
	l.append(3 ** i)
a = [[] for i in range(40)]
for i in range(n):
	for j in range(39, -1, -1):
		if li[i] % l[j] == 0:
			a[j].append(li[i])
			break
for i in range(39, -1, -1):
	if len(a[i]) == 0:
		continue
	a[i].sort()
	print(*a[i], sep=' ', end=' ')


from bisect import bisect_left
found = []

def binary_search(a, x, lo=0, hi=None):
	hi = hi or len(a)
	pos = bisect_left(a, x, lo, hi)
	return a[pos] if pos != hi and a[pos] == x else None

def find_candidates(a, val, n, candidates):
	global found
	if n == len(candidates) + 1:
		found = candidates + [val]
		raise ValueError()
	a.remove(val)
	candidates.append(val)
	first_candidate = binary_search(a, val * 2)
	second_candidate = None
	if val % 3 == 0:
		second_candidate = binary_search(a, val // 3)
	if first_candidate:
		find_candidates(a, first_candidate, n, candidates[:])
	if second_candidate:
		find_candidates(a, second_candidate, n, candidates[:])

def go():
	global found
	n = int(input())
	a = [int(i) for i in input().split(' ')]
	a.sort()
	for val in a:
		try:
			option = find_candidates(a[:], val, n, [])
		except ValueError:
			found = [str(f) for f in found]
			return ' '.join(found)
print(go())


def comp(n):
	i = 0
	while n % 2 == 0:
		i += 1
		n /= 2
	return (-n, i)
rd = lambda : list(map(int, input().split()))
n = rd()
a = sorted(rd(), key=comp)
print(*a)


n = int(input())
a = list(map(int, input().split()))
g = [[] for i in range(n)]
for i in range(n):
	for j in range(n):
		if a[i] * 3 == a[j]:
			g[j].append(i)
		if a[i] == a[j] * 2:
			g[j].append(i)
s = -1
for i in range(n):
	if len(g[i]) == 0:
		s = i
		break
x = a[s]
l = [x]
for i in range(n - 1):
	if x * 3 in a:
		l.append(x * 3)
		x = x * 3
	else:
		l.append(x // 2)
		x = x // 2
print(*l[::-1])


import sys
n = int(input())
seq = list(map(int, input().split()))
used = [False] * n

def A_n_k_pythonic(a, curr, depth=0):
	if depth == len(a):
		print(' '.join(map(str, curr)))
		sys.exit()
	for i in range(len(a)):
		if not used[i]:
			if not curr or curr[-1] == a[i] * 3 or curr[-1] * 2 == a[i]:
				curr.append(a[i])
				used[i] = True
				A_n_k_pythonic(a, curr, depth + 1)
				curr.pop()
				used[i] = False
A_n_k_pythonic(seq, [])


def three(x):
	c = 0
	while x % 3 == 0:
		x //= 3
		c += 1
	return c

def two(x):
	c = 0
	while x % 2 == 0:
		x //= 2
		c += 1
	return c
n = int(input())
a = list(map(int, input().split()))
D = [[0, 0, 0] for i in range(n)]
for i in range(n):
	D[i][0] = a[i]
	D[i][1] = three(a[i])
	D[i][2] = two(a[i])
for j in range(len(D) - 1):
	for i in range(len(D) - 1):
		if D[i][1] < D[i + 1][1]:
			(D[i], D[i + 1]) = (D[i + 1], D[i])
for j in range(len(D) - 1):
	for i in range(len(D) - 1):
		if D[i][2] > D[i + 1][2]:
			(D[i], D[i + 1]) = (D[i + 1], D[i])
for i in D:
	print(i[0], end=' ')


from math import sqrt, gcd, ceil, floor, log, factorial
from itertools import permutations, combinations
from collections import Counter, defaultdict

def dfs(d, node, visited, res):
	visited.append(node)
	res.append(node)
	for i in d[node]:
		if i not in visited:
			dfs(d, i, visited, res)
n = int(input())
a = list(map(int, input().split()))
d = defaultdict(list)
for i in a:
	d[i] = list(filter(lambda x: x / i == 2.0 or i / x == 3.0, a))
flag = 0
for key in d:
	res = [key]
	for i in d[key]:
		visited = []
		dfs(d, i, visited, res)
		if len(res) == n:
			flag = 1
			break
	if flag == 1:
		break
print(*res)


__file__ = 0

def input_():
	global __file__
	if not __file__:
		return input()
	if not hasattr(__file__, 'readline'):
		__file__ = open('input.txt', 'r')
	return __file__.readline()
n = int(input_())
arr = list(map(int, input_().split()))

def factor_counter(x, factor):
	count = 0
	while True:
		if x % factor:
			return count
		else:
			count += 1
			x = x // factor
arr = sorted(arr, key=lambda x: (-factor_counter(x, 3), factor_counter(x, 2)))
print(' '.join(map(str, arr)))


from collections import deque
from copy import deepcopy

def read():
	return int(input())

def readlist():
	return list(map(int, input().split()))

def readmap():
	return map(int, input().split())
N = read()
A = readlist()
graph = {}
for i in range(N):
	graph[i + 1] = []
for i in range(N):
	for j in range(N):
		if A[i] % 3 == 0 and A[i] // 3 == A[j] or A[i] * 2 == A[j]:
			graph[i + 1].append(j + 1)

def __logging(visited, rest=[]):
	if rest:
		print('visited:%s\n   rest:%s\n' % (visited, rest))
	else:
		print('visited:%s' % visited)

def dfs(graph, start):
	stack = [start]
	visited = []
	while stack:
		label = stack.pop()
		if len(visited) == len(graph):
			visited.append(label)
			return visited
		if label not in visited:
			visited.append(label)
			stack = stack + graph.get(label, [])
	return visited
for i in range(N):
	if len(dfs(graph, i + 1)) == N:
		lst = dfs(graph, i + 1)
		for j in range(N):
			lst[j] = A[lst[j] - 1]
		print(' '.join(list(map(str, lst))))


n = int(input())
a = [int(x) for x in input().split()]
for i in range(n):
	ans = list()
	ans.append(a[i])
	for j in range(n):
		if i != j:
			if ans[-1] * 2 in a:
				ans.append(ans[-1] * 2)
			elif ans[-1] % 3 == 0:
				if ans[-1] // 3 in a:
					ans.append(ans[-1] // 3)
	if len(ans) == n:
		print(*ans)
		break


from sys import stdin, stdout
cin = stdin.readline
cout = stdout.write
n = int(cin())
a = list(map(int, cin().split()))
l = [0] * n
for i in a:
	l[0] = i
	for j in range(n - 1):
		if l[j] % 3 == 0 and l[j] // 3 in a:
			l[j + 1] = l[j] // 3
		elif l[j] * 2 in a:
			l[j + 1] = l[j] * 2
		else:
			break
	else:
		for j in l:
			cout(str(j) + ' ')


def canTake(nbr, lst, dict):
	return dict[nbr] != lst.count(nbr)

def exists(nbr, dict):
	return nbr in dict

def dfs(nbr, lst, dict, n):
	if len(lst) == n:
		return lst
	possibilities = []
	if exists(nbr * 2, dict) and canTake(nbr * 2, lst, dict):
		possibilities.append(nbr * 2)
	if nbr % 3 == 0 and exists(nbr // 3, dict) and canTake(nbr // 3, lst, dict):
		possibilities.append(nbr // 3)
	if len(possibilities) == 0:
		return []
	res = []
	for item in possibilities:
		newLst = list(lst)
		newLst.append(item)
		res.append(dfs(item, newLst, dict, n))
	return max(res, key=len)

def main():
	n = int(input())
	arr = map(int, input().split())
	dict = {}
	for item in arr:
		if exists(item, dict):
			dict[item] += 1
		else:
			dict[item] = 1
	res = []
	for item in dict:
		res.append(dfs(item, [item], dict, n))
	print(' '.join((str(x) for x in max(res, key=len))))
main()


n = int(input())
l = [int(e) for e in input().split()]
dic = {}
for i in l:
	if i in dic:
		dic[i] += 1
	else:
		dic[i] = 1
res = []

def dfs(res):
	temp = res[-1]
	tempLen = len(res)
	if temp % 3 == 0:
		tempDiv = temp // 3
		if tempDiv in dic and dic[tempDiv] > 0:
			res.append(tempDiv)
			dic[tempDiv] -= 1
			dfs(res)
			if len(res) == n:
				return res
			else:
				res = res[0:tempLen]
				dic[tempDiv] += 1
				temp = res[-1]
	tempDiv = temp * 2
	if tempDiv in dic and dic[tempDiv] > 0:
		res.append(tempDiv)
		dic[tempDiv] -= 1
		dfs(res)
		if len(res) == n:
			return res
		else:
			res = res[0:tempLen]
			dic[tempDiv] += 1
			temp = res[-1]
	return res
for i in range(0, n):
	res = [l[i]]
	res = dfs(res)
	if len(res) == n:
		break
for i in res:
	print(i, end=' ')


n = int(input())
a = list(map(int, input().split()))
for i in range(n):
	start = a[i]
	ans = [start]
	f = True
	for j in range(n - 1):
		if start * 2 in a:
			ans.append(start * 2)
			start *= 2
		elif start % 3 == 0 and start // 3 in a:
			ans.append(start // 3)
			start //= 3
		else:
			f = False
			break
	if f:
		break
print(*ans)


import math
import collections

def power(x):
	cnt = 0
	while x % 3 == 0:
		cnt += 1
		x //= 3
	return cnt
n = int(input())
l = [[0, int(x)] for x in input().split()]
for i in range(n):
	l[i][0] = -power(l[i][1])
l.sort()
for i in range(n):
	print(l[i][1], end=' ')
print()


def vert(n):
	if n * 2 in a:
		yield (n * 2)
	if n % 3 == 0 and n // 3 in a:
		yield (n // 3)

def dfs(i, arr, b):
	if len(arr) == n:
		print(' '.join(map(str, arr)))
		return
	for j in vert(i):
		c = b.copy()
		c.remove(j)
		dfs(j, arr + [j], c)
n = int(input())
a = set([int(i) for i in input().split()])
for i in a:
	l = []
	b = a.copy()
	b.remove(i)
	dfs(i, l + [i], b)


n = int(input())
a = list(map(int, input().strip().split()))
l = []
for i in a:
	k = 0
	k = i
	c = 0
	while k % 3 == 0:
		k = k // 3
		c += 1
	p = -c
	l.append([p, i])
l.sort()
res = []
for i in l:
	res.append(i[1])
print(' '.join(map(str, res)))


from collections import defaultdict
n = int(input())
arr = [int(item) for item in input().split(' ')]
for x in arr:
	d = defaultdict(lambda : 0)
	for item in arr:
		d[item] += 1
	ptr = x
	covered = 1
	d[ptr] -= 1
	seq = [ptr]
	while covered < n:
		a = ptr * 2
		b = None
		if ptr % 3 == 0:
			b = ptr // 3
		if b and d[b]:
			ptr = b
		elif d[a]:
			ptr = a
		else:
			break
		seq.append(ptr)
		d[ptr] -= 1
		if d[ptr] < 0:
			break
		covered += 1
	if covered == n:
		print(' '.join(map(str, seq)))
		exit()


n = int(input())
a = list(map(int, input().split()))
ind = -1
for i in range(n):
	ta = a.copy()
	cur = a[i]
	ta.pop(i)
	res = [cur]
	while ta:
		if ta.count(cur * 2):
			res.append(cur * 2)
			ta.pop(ta.index(cur * 2))
			cur *= 2
		elif cur % 3 == 0 and ta.count(cur // 3):
			res.append(cur // 3)
			ta.pop(ta.index(cur // 3))
			cur //= 3
		else:
			break
	if len(res) == n:
		print(*res)
		break


def gcd1(a, b):
	return a if b == 0 else gcd1(b, a % b)

def gcd2(arr):
	ans = arr[0]
	for i in arr:
		ans = gcd1(ans, i)
	return ans

def deg(a):
	ans = [0, 0]
	while a % 2 == 0:
		a //= 2
		ans[0] += 1
	while a % 3 == 0:
		a //= 3
		ans[1] += 1
	return ans

def upg(a, gcd):
	return pow(2, a[0]) * pow(3, a[1]) * gcd
n = int(input())
arr = [int(s) for s in input().split()]
gcd = gcd2(arr)
for i in range(len(arr)):
	arr[i] //= gcd
	t = deg(arr[i])
	arr[i] = [t[1] - t[0], t]
arr = sorted(arr)[::-1]
for i in arr:
	print(upg(i[1], gcd), end=' ')


import sys
import math

def get_ints():
	return map(int, sys.stdin.readline().strip().split())

def get_list():
	return list(map(int, sys.stdin.readline().strip().split()))

def get_string():
	return sys.stdin.readline().strip()
for t in range(1):
	n = int(input())
	arr = get_list()
	for i in range(n):
		x = arr[i]
		new_arr = arr[:i] + arr[i + 1:]
		ans = [x]
		pos = 0
		while len(ans) < n:
			multi = ans[pos] * 2
			if multi in new_arr:
				ans.append(multi)
				new_arr.remove(multi)
			elif ans[pos] % 3 != 0:
				break
			else:
				divide = ans[pos] // 3
				if divide in new_arr:
					ans.append(divide)
					new_arr.remove(divide)
				else:
					break
			pos += 1
		if len(ans) == n:
			print(*ans)
			break


n = int(input())
nums = list(map(int, input().split()))
nums.sort()
ans = []
for i in range(n):
	aux = nums[:]
	a = [nums[i]]
	j = 0
	while a[j] // 3 in aux or a[j] * 2 in aux:
		b = a[j] // 3
		c = a[j] * 2
		if c in aux:
			a.append(c)
			aux.remove(c)
		elif a[j] == 4:
			break
		else:
			a.append(b)
			aux.remove(b)
		j += 1
	ans.append(a)
ans.sort(key=len)
for item in ans[-1]:
	print(item, end=' ')


n = int(input())
l = list(map(int, input().split()))

def fact(n):
	m = n
	(c, c1) = (0, 0)
	while n % 2 == 0:
		n = n // 2
		c += 1
	while n % 3 == 0:
		n = n // 3
		c1 += 1
	return (c1, -c, m)
l1 = []
for i in l:
	l1.append(fact(i))
l1.sort(reverse=True)
for i in range(n):
	print(l1[i][2], end=' ')


import collections
n = int(input())
lis = [*map(int, input().split())]
li1 = []
li2 = []
li3 = collections.deque()
for i in lis:
	if i % 3 == 0 and i % 2 != 0:
		li2.append(i)
	elif i % 3 != 0 and i % 2 == 0:
		li1.append(i)
	else:
		li3.append(i)
li1.sort()
li2.sort(reverse=True)
temp = collections.deque()
if len(li3) >= 1:
	temp.append(li3.pop())
while li3:
	se = temp[-1]
	if se // 3 in li3:
		temp.append(se // 3)
		li3.remove(se // 3)
	elif se * 2 in li3:
		temp.append(se * 2)
		li3.remove(se * 2)
	else:
		break
while li3:
	se = temp[0]
	if se // 2 in li3:
		se = se // 2
		temp.appendleft(se)
		li3.remove(se)
	elif se * 3 in li3:
		se = se * 3
		temp.appendleft(se)
		li3.remove(se)
	else:
		break
print(*li2, *temp, *li1, sep=' ')


n = int(input())

def calc(x0):
	(v2, v3) = (0, 0)
	x = int(x0)
	while x % 3 == 0:
		v3 += 1
		x = x // 3
	while x % 2 == 0:
		v2 += 1
		x = x // 2
	return tuple([v2, -v3, x0])
a = list(map(calc, input().split()))
a = sorted(a)
print(' '.join(map(lambda x: str(x[2]), a)))


def cmp(x):
	i = 0
	while x % 2 == 0:
		i += 1
		x /= 2
	return (-x, i)

def main():
	n = int(input())
	a = list(map(int, input().split()))
	a.sort(key=cmp)
	for i in range(len(a)):
		print(a[i], end=' ')
main()


n = int(input())
s = list(map(int, input().split()))
sett = set(s)
last = s[0]
while True:
	if last % 3 == 0 and last // 3 in sett:
		last = last // 3
	elif last * 2 in sett:
		last = last * 2
	else:
		break
arr = [last]
while True:
	if last % 2 == 0 and last // 2 in sett:
		last = last // 2
		arr += [last]
	elif last * 3 in sett:
		last = last * 3
		arr += [last]
	else:
		break
arr = arr[::-1]
print(' '.join(list(map(str, arr))))


n = int(input())
t = [*map(int, input().split())]
x = []
for i in t:
	(twoCnt, threeCnt) = (0, 0)
	tt = i
	while tt % 2 == 0:
		tt //= 2
		twoCnt += 1
	tt = i
	while tt % 3 == 0:
		tt //= 3
		threeCnt += 1
	x.append([i, twoCnt, threeCnt])
x.sort(key=lambda x: (-x[2], x[1]))
for i in x:
	print(i[0], end=' ')


def to(a):
	s = 0
	while a % 2 == 0 and a != 0:
		s += 1
		a = a // 2
	return s

def tr(a):
	s = 0
	while a % 3 == 0 and a != 0:
		s += 1
		a = a // 3
	return s
n = int(input())
a = list(map(int, input().split()))
for i in range(n):
	for j in range(i + 1, n):
		if to(a[i]) > to(a[j]):
			(a[i], a[j]) = (a[j], a[i])
		if tr(a[i]) < tr(a[j]):
			(a[i], a[j]) = (a[j], a[i])
print(*a)


from collections import deque
n = int(input())
nums = [int(x) for x in input().split(' ')]
nums.sort()
answer = deque()
answer.append(nums.pop())
k = 0
while len(nums) != 0:
	nowLeft = answer[0]
	nowRight = answer[len(answer) - 1]
	swap_pos = 0
	left = 0
	for (i, num) in enumerate(nums):
		if nowLeft == num * 2 or (num % 3 == 0 and num // 3 == nowLeft):
			swap_pos = i
			left = 1
			break
		if nowRight * 2 == num or (nowRight % 3 == 0 and num == nowRight // 3):
			swap_pos = i
			left = -1
			break
	if left == 1:
		answer.appendleft(nums[swap_pos])
		(nums[swap_pos], nums[len(nums) - 1]) = (nums[len(nums) - 1], nums[swap_pos])
		nums.pop()
	elif left == -1:
		answer.append(nums[swap_pos])
		(nums[swap_pos], nums[len(nums) - 1]) = (nums[len(nums) - 1], nums[swap_pos])
		nums.pop()
for num in answer:
	print(num, end=' ')


from collections import defaultdict
memo = []
n = 0

class Graph:

	def __init__(self):
		self.graph = defaultdict(list)

	def addEdge(self, u, v):
		self.graph[u].append(v)

	def DFS(self):
		for key in dict(self.graph).keys():
			memo.append(key)
			memo.append(*dict(self.graph)[key])
			while len(memo) < n:
				try:
					key = dict(self.graph)[key][0]
					memo.append(*dict(self.graph)[key])
				except KeyError:
					break
			if len(memo) == n:
				break
			else:
				memo.clear()
n = numberOfedges = int(input())
numbers = list(map(int, input().split()))
(oddHead, Hi) = (numbers[0], 0)
(evenHead, Li) = (numbers[0], 0)
for i in range(len(numbers)):
	if numbers[i] % 3 == 0 and oddHead < numbers[i]:
		oddHead = numbers[i]
		Hi = i
	if numbers[i] % 2 and evenHead > numbers[i]:
		evenHead = numbers[i]
		Li = i
if oddHead != 0:
	(numbers[0], numbers[Hi]) = (numbers[Hi], numbers[0])
else:
	(numbers[0], numbers[Li]) = (numbers[Li], numbers[0])
edges = []
g = Graph()
for x in range(len(numbers)):
	flag = 0
	for y in range(len(numbers)):
		if numbers[y] == numbers[x] * 2 or (numbers[x] % 3 == 0 and numbers[x] // 3 == numbers[y]):
			edges.append([numbers[x], numbers[y]])
			flag += 1
			if flag == 2:
				break
for i in edges:
	g.addEdge(i[0], i[1])
g.DFS()
print(*memo)


n = int(input())
A = [int(x) for x in input().split()]
S = set(A)
ADJ = {}
for elem in A:
	adjs = []
	if elem * 2 in S:
		adjs.append(elem * 2)
	if elem % 3 == 0 and elem // 3 in S:
		adjs.append(elem // 3)
	ADJ[elem] = adjs

def solve(V, L):
	myL = list(L)
	myL.append(V)
	if len(myL) == len(A):
		return myL
	for i in ADJ[V]:
		resp = solve(i, myL)
		if resp:
			return resp
	return None
for elem in A:
	resp = solve(elem, [])
	if resp:
		print(' '.join(map(str, resp)))
		break


import collections
n = int(input())
arr = list(map(int, input().split()))
arr = sorted(arr)
ans = collections.deque()
ans.append(arr[0])
while len(ans) < n:
	for i in range(n):
		if arr[i] == 0:
			continue
		front = ans[0]
		back = ans[len(ans) - 1]
		if arr[i] == front * 3:
			ans.insert(0, arr[i])
			arr[i] = 0
			break
		if arr[i] * 3 == back:
			ans.append(arr[i])
			arr[i] = 0
			break
		if arr[i] * 2 == front:
			ans.insert(0, arr[i])
			arr[i] = 0
			break
		if arr[i] == back * 2:
			ans.append(arr[i])
			arr[i] = 0
			break
for i in range(len(ans)):
	print(ans[i], end=' ')
print()


def pow3(a):
	if a % 3 != 0:
		return 0
	return 1 + pow3(a // 3)
n = int(input())
a = list(map(int, input().split()))
b = []
for i in a:
	b.append((-pow3(i), i))
b.sort()
for i in b:
	print(i[1], end=' ')


n = int(input())
l = [int(x) for x in input().split()]

def key(x, r=0):
	while x % 3 == 0:
		x //= 3
		r -= 1
	while x % 2 == 0:
		x //= 2
		r += 1
	return r
print(*sorted(l, key=key))


from collections import deque

def main():
	n = int(input())
	visit = set(list(map(int, input().split(' '))))
	dq = deque([visit.pop()])
	while len(dq) < n:
		b = dq[-1]
		if b * 2 in visit:
			dq.append(b * 2)
		elif b % 3 == 0 and b // 3 in visit:
			dq.append(b // 3)
		f = dq[0]
		if f * 3 in visit:
			dq.appendleft(f * 3)
		elif f % 2 == 0 and f // 2 in visit:
			dq.appendleft(f // 2)
	print(' '.join(map(str, dq)))
main()


from collections import deque

def find_loop(n, e, flag):
	x = [0] * n
	d = deque()
	t = []
	c = 0
	for i in range(n):
		for j in e[i]:
			x[j] += 1
	for i in range(n):
		if x[i] == 0:
			d.append(i)
			t.append(i)
			c += 1
	while d:
		i = d.popleft()
		for j in e[i]:
			x[j] -= 1
			if x[j] == 0:
				d.append(j)
				t.append(j)
				c += 1
	if flag == 0:
		return c == n
	else:
		return t
n = int(input())
a = list(map(int, input().split()))
edge = [[] for _ in range(n)]
for i in range(n):
	for j in range(n):
		if a[i] * 3 == a[j]:
			edge[j].append(i)
		if a[i] * 2 == a[j]:
			edge[i].append(j)
d = find_loop(n, edge, 1)
print(*[a[i] for i in d])


n = int(input())
arr = list(map(int, input().split()))
edge = []
for i in arr:
	flag = 0
	if i * 3 in arr:
		edge.append([i * 3, i])
		flag += 1
	if i % 2 == 0 and i // 2 in arr:
		edge.append([i // 2, i])
		flag += 1
	if flag == 0:
		edge.append([-1, i])
		x = arr.index(i)
l = len(edge)
temp = edge[x][1]
print(temp, end=' ')
for i in range(n - 1):
	for j in range(l):
		if edge[j][0] == temp:
			print(edge[j][1], end=' ')
			temp = edge[j][1]
			break


(z, zz) = (input, lambda : list(map(int, z().split())))
zzz = lambda : [int(i) for i in stdin.readline().split()]
(szz, graph, mod, szzz) = (lambda : sorted(zz()), {}, 10 ** 9 + 7, lambda : sorted(zzz()))
from string import *
from re import *
from collections import *
from queue import *
from sys import *
from collections import *
from math import *
from heapq import *
from itertools import *
from bisect import *
from collections import Counter as cc
from math import factorial as f
from bisect import bisect as bs
from bisect import bisect_left as bsl
from itertools import accumulate as ac

def lcd(xnum1, xnum2):
	return xnum1 * xnum2 // gcd(xnum1, xnum2)

def prime(x):
	p = ceil(x ** 0.5) + 1
	for i in range(2, p):
		if x % i == 0 and x != 2 or x == 0:
			return 0
	return 1

def dfs(u, visit, graph):
	visit[u] = True
	for i in graph[u]:
		if not visit[i]:
			dfs(i, visit, graph)
n = int(z())
l = szzz()
for i in range(1, n + 1):
	x = l[-i]
	lst = [x]
	for j in range(n):
		if x % 3 == 0 and x // 3 in l:
			lst.append(x // 3)
			x = x // 3
		elif x * 2 in l:
			lst.append(x * 2)
			x = x * 2
		else:
			break
	if l == sorted(lst):
		print(*lst)
		exit()


import copy
import sys
x = int(input())
nums = list(map(int, input().split()))

def choose(s, i, n):
	if len(s) == x:
		for i in s:
			print(i, end=' ')
		sys.exit()
	for j in n:
		if s[i] * 2 == j or s[i] / 3 == float(j):
			new_n = copy.copy(n)
			new_n.remove(j)
			choose(s + [j], i + 1, new_n)
for k in nums:
	n = copy.copy(nums)
	n.remove(k)
	choose([k], 0, n)


from sys import stdin
from collections import *

def arr_inp(n):
	if n == 1:
		return [int(x) for x in stdin.readline().split()]
	elif n == 2:
		return [float(x) for x in stdin.readline().split()]
	else:
		return list(stdin.readline()[:-1])
(n, a) = (int(input()), sorted(arr_inp(1)))
(c, de) = (Counter(a), deque([a[-1]]))
c[a[-1]] -= 1
while True:
	if de[-1] % 3 == 0 and c[de[-1] // 3] > 0:
		c[de[-1] // 3] -= 1
		de.append(de[-1] // 3)
	elif c[de[-1] * 2] > 0:
		c[de[-1] * 2] -= 1
		de.append(de[-1] * 2)
	else:
		break
while True:
	if de[0] % 2 == 0 and c[de[0] // 2] > 0:
		c[de[0] // 2] -= 1
		de.appendleft(de[0] // 2)
	elif c[de[0] * 3] > 0:
		c[de[0] * 3] -= 1
		de.appendleft(de[0] * 3)
	else:
		break
print(*de)


from collections import defaultdict

def div_by_3(n):
	i = 0
	while n % 3 == 0:
		n = n // 3
		i += 1
	return i
n = int(input())
seq = [int(x) for x in input().split(' ')]
order = defaultdict(list)
for element in seq:
	order[div_by_3(element)].append(element)
keys = sorted(order.keys(), reverse=True)
result = ''
for key in keys:
	result += ' '.join((str(x) for x in sorted(order[key]))) + ' '
print(result.strip())


n = int(input())
res = list(map(int, input().strip().split(' ')))
res = sorted(res, reverse=True)
for i in range(len(res)):
	k = 0
	result = []
	result.append(res[i])
	while len(result) != len(res):
		if result[k] % 3 == 0 and result[k] // 3 in res:
			result.append(result[k] // 3)
		elif result[k] * 2 in res:
			result.append(result[k] * 2)
		else:
			break
		if len(result) == len(res):
			break
		k += 1
	if len(result) == len(res):
		break
for i in result:
	print(i, end=' ')


I = lambda : int(input())
IL = lambda : list(map(int, input().split()))
IF = lambda : list(map(float, input().split()))
n = I()
A = IL()
A.sort(key=lambda x: (x & -x, -x))
print(*A)


import sys
n = int(sys.stdin.readline().strip())
l2 = sys.stdin.readline().strip().split(' ')
l = [int(i) for i in l2]
dic = {i for i in l}
pairing = {}
sequence = []
for i in range(n):
	temp = [[], []]
	num = l[i]
	f1 = num * 3
	if num % 2 == 0:
		f2 = num // 2
		if f2 in dic:
			temp[0].append(f2)
	b1 = num * 2
	if num % 3 == 0:
		b2 = num // 3
		if b2 in dic:
			temp[1].append(b2)
	if f1 in dic:
		temp[0].append(f1)
	if b1 in dic:
		temp[1].append(b1)
	pairing[l[i]] = temp
bs = []
for key in pairing:
	f = pairing[key][0]
	b = pairing[key][1]
	if len(b) != 0:
		for item in b:
			bs.append(item)
	for front in f:
		if key in pairing[front][1]:
			sequence.append((front, key))
head = [i for i in l if i not in bs]
p = head[0]
output = ''
for i in range(n - 1):
	output += str(p) + ' '
	temp = [x for x in sequence if x[0] == p]
	nextt = temp[0][1]
	p = nextt
	if i == n - 2:
		output += str(p)
print(output)


n = int(input())
G = list(map(int, input().split()))
M = [[] for i in range(n)]
for i in range(len(G)):
	for j in range(len(G)):
		if G[i] == G[j] * 3 or G[i] * 2 == G[j]:
			M[i].append(j)
used = [0] * n

def FindPath(k, m):
	if m == len(G):
		Z.append(R[:])
	else:
		for i in M[k]:
			if used[i] == 0 and len(Z) == 0:
				R.append(G[i])
				used[i] = 1
				FindPath(i, m + 1)
				R.pop()
				used[i] = 0
for i in range(n):
	used = [0] * n
	used[i] = 1
	R = [G[i]]
	Z = []
	FindPath(i, 1)
	if len(Z) > 0:
		Z = [str(i) for i in Z[0]]
		print(' '.join(Z))
		break


def test(l, m, ite, Mite, dest):
	if ite == Mite:
		return True
	dest.append(m)
	if m not in l:
		dest.pop()
		return False
	if m % 3 == 0:
		if test(l, m // 3, ite + 1, Mite, dest):
			return True
		else:
			return test(l, m * 2, ite + 1, Mite, dest)
	else:
		return test(l, m * 2, ite + 1, Mite, dest)
n = int(input())
line = [int(e) for e in input().split(' ')]
possible = []
rez = -1
de = []
for e in line:
	if not test(line, e, 0, n, de):
		de.clear()
	else:
		break
for e in de:
	print(e, end=' ')
print()


from sys import stdin
from operator import itemgetter

def calc(x):
	res = 0
	while x % 3 == 0:
		res += 1
		x //= 3
	return res
n = int(stdin.readline())
tup = []
arr = list(map(int, stdin.readline().split()))
for i in arr:
	res = calc(i)
	tup.append((-res, i))
tup.sort(key=itemgetter(0, 1))
for i in tup:
	print(i[1], end=' ')


n = int(input())
a = list(map(int, input().split()))
b = [0] * n
for i in range(n):
	x = a[i]
	y = 0
	while x % 3 == 0:
		y += 1
		x = x // 3
	b[i] = y
d = []
maxi = max(b)
while maxi > -1:
	c = []
	for i in range(n):
		if b[i] == maxi:
			c.append(a[i])
	c = sorted(c)
	for i in range(len(c)):
		d.append(c[i])
	maxi -= 1
s = ''
for i in range(len(d)):
	s += str(d[i]) + ' '
print(s)


n = int(input())
a = [int(x) for x in input().split(' ')]
ss = set()
for x in a:
	ss.add(x)
yy = dict()
ini = None
for x in a:
	if 2 * x in ss:
		yy[2 * x] = x
	elif x % 3 == 0 and x // 3 in ss:
		yy[x // 3] = x
	else:
		ini = x
ans = [ini]
cur = ini
while cur in yy.keys():
	cur = yy[cur]
	ans.append(cur)
ans = ans[::-1]
res = ''
for i in range(n):
	if i > 0:
		res += ' '
	res += str(ans[i])
print(res)


n = int(input().strip())
ais = list(map(int, input().strip().split()))

def d2d3(x):
	res = 0
	while x % 2 == 0:
		x //= 2
		res += 1
	while x % 3 == 0:
		x //= 3
		res -= 1
	return res
ais.sort(key=d2d3)
print(' '.join(map(str, ais)))


n = int(input())
a = [int(a) for a in input().split()]
ans = []
if n == 2:
	if a[1] * 2 == a[0] or a[1] / 3 == a[0]:
		ans.append(a[1])
		ans.append(a[0])
	else:
		ans.append(a[0])
		ans.append(a[1])
else:
	while a:
		for i in a:
			if i / 2 not in a and i * 3 not in a:
				ans.append(i)
				a.remove(i)
for i in ans:
	print(i, end=' ')


def func(n, m):
	m = m.split()
	m = [int(m[i]) for i in range(len(m))]
	result = [m[0]]
	count = 0
	countall = 0
	m.sort(key=lambda p: (-power(p)[1], power(p)[0]))
	return ' '.join((str(m[i]) for i in range(len(m))))

def power(n):
	double = 0
	triple = 0
	while n % 2 == 0 or n % 3 == 0:
		if n % 2 == 0:
			n = n // 2
			double += 1
		if n % 3 == 0:
			n = n // 3
			triple += 1
	return [double, triple]
t = [1] + [2 ** i for i in range(99, 0, -1)]
print(func(int(input().strip()), input().strip()))


n = int(input())
a = list(map(int, input().split()))
sa = set(a)

def dfs(node, li):
	if len(li) == n:
		print(*li)
		exit(0)
	if node * 2 in sa:
		dfs(node * 2, li + [node * 2])
	if node % 3 == 0 and node // 3 in sa:
		dfs(node // 3, li + [node // 3])
for i in range(n):
	dfs(a[i], [a[i]])


def key(d, n):
	for i in d:
		if d[i] == n:
			return i
	return -1
n = int(input())
l = [int(i) for i in input().split()]
d = {}
for i in range(n):
	if l[i] % 3 == 0:
		d[l[i]] = [l[i] // 3, l[i] * 2]
	else:
		d[l[i]] = [l[i] * 2]
for i in d:
	c = 1
	for j in d[i]:
		if j in d:
			c = 0
			d[i] = j
	if c == 1:
		d[i] = []
		k = i
l1 = [k]
while key(d, k) != -1:
	k1 = key(d, k)
	l1.append(k1)
	k = k1
print(*l1[::-1])


def in_power(a):
	ans = 0
	while a % 3 == 0:
		a = a // 3
		ans += 1
	return ans

def main():
	n = int(input())
	numbers = [int(i) for i in input().split()]
	ans = [''] * n
	for i in range(n):
		ans[i] = (-in_power(numbers[i]), numbers[i])
	ans.sort()
	for i in range(n):
		print(ans[i][1], end=' ')
main()


def count(x):
	res = 0
	while x % 3 == 0:
		res += 1
		x //= 3
	return res
n = int(input())
l = list(map(int, input().split()))
ans = []
for i in range(n):
	ans.append([0, l[i]])
for i in range(n):
	ans[i][0] = -count(l[i])
ans.sort()
for i in range(n):
	print(ans[i][1], end=' ')


n = int(input())
l = list(map(int, input().split()))
l.sort()
l1 = []
l2 = []
cur = l[0]
l1.append(cur)
while True:
	if cur % 3 == 0 and cur // 3 in l:
		cur //= 3
		l1.append(cur)
	elif cur * 2 in l:
		cur *= 2
		l1.append(cur)
	else:
		break
cur = l[0]
while True:
	if cur % 2 == 0 and cur // 2 in l:
		cur //= 2
		l2.append(cur)
	elif cur * 3 in l:
		cur *= 3
		l2.append(cur)
	else:
		break
for x in reversed(l2):
	print(x, end=' ')
for x in l1:
	print(x, end=' ')


def dfs(i, visit, ans0, cnt):
	if cnt == n:
		ans = [a[ans0[j]] for j in range(n)]
		print(*ans)
		exit()
	for j in G[i]:
		if not visit[j]:
			visit[j] = 1
			ans0[cnt] = j
			dfs(j, visit, ans0, cnt + 1)
			visit[j] = 0
n = int(input())
a = list(map(int, input().split()))
G = [[] for _ in range(n)]
for i in range(n):
	for j in range(n):
		if 2 * a[i] == a[j] or a[i] == 3 * a[j]:
			G[i].append(j)
for i in range(n):
	visit = [0] * n
	ans0 = [-1] * n
	visit[i] = 1
	ans0[0] = i
	dfs(i, visit, ans0, 1)


def f(x, k):
	cnt = 0
	while x % k == 0:
		x = x // k
		cnt += 1
	return cnt
n = int(input())
a = map(int, input().split())
print(*sorted(a, key=lambda x: [f(x, 2), -f(x, 3)]))


from collections import deque

def bfs(node):
	q = deque()
	q.append(node)
	k = [node]
	while q:
		node = q.popleft()
		if node not in k:
			k.append(node)
		for child in g[node]:
			if child not in q:
				q.append(child)
	return (k, len(k))
n = int(input())
l = list(map(int, input().split()))
g = {}
for i in l:
	g[i] = g.get(i, [])
	if 2 * i in l:
		g[i].append(2 * i)
	if i % 3 == 0 and i // 3 in l:
		g[i].append(i // 3)
for i in g:
	p = bfs(i)
	if p[1] == n:
		print(*p[0])
		break


n = int(input())
l = list(map(int, input().split()))
ans = []
for i in range(n):
	x = l[i]
	cnt = 0
	while l[i] % 2 == 0:
		cnt += 1
		l[i] //= 2
	while l[i] % 3 == 0:
		cnt -= 1
		l[i] //= 3
	ans.append([cnt, x])
ans.sort()
print(*(i[1] for i in ans))


from sys import stdin, stdout

def rearrage_polycarp_backtracking(n: int, sequence):
	poly = set(sequence)

	def recurse(start: int, path=[], seen=set()) -> bool:
		if start not in poly or start in seen:
			return []
		path.append(start)
		seen.add(start)
		if len(recurse(2 * start, path, seen)) == n:
			return path
		if start % 3 == 0 and len(recurse(start // 3, path, seen)) == n:
			return path
		if len(path) != n:
			seen.remove(path.pop())
		return path
	i = 0
	while i < n:
		path = recurse(sequence[i], [], set())
		if path:
			return path
		i += 1

def rearrage_polycarp_math_and_sorting_solution(n: int, sequence):

	def exp(b: int, a: int) -> int:
		k = 0
		while a % b == 0:
			k += 1
			a //= b
		return k
	power_of_3 = [(-exp(3, num), num) for num in sequence]
	power_of_3.sort()
	return [num[1] for num in power_of_3]

def rearrage_polycarp(n: int, sequence):
	polys_seq = set(sequence)
	ordered_seq = [num for num in sequence if not (num % 2 == 0 and num // 2 in polys_seq or 3 * num in polys_seq)]
	n -= 1
	i = 0
	while n:
		if 2 * ordered_seq[i] in polys_seq:
			ordered_seq.append(2 * ordered_seq[i])
		else:
			ordered_seq.append(ordered_seq[i] // 3)
		n -= 1
		i += 1
	return ordered_seq
n = int(stdin.readline().rstrip())
sequence = [int(x) for x in stdin.readline().rstrip().split(' ')]
stdout.write(' '.join((str(num) for num in rearrage_polycarp_backtracking(n, sequence))) + '\n')


from heapq import heappop, heappush
n = int(input())
a = []
c = input().split()
for i in c:
	i = int(i)
	p = 0
	while not i % 3:
		i //= 3
		p += 1
	a += [[] for j in range(p - len(a) + 1)]
	heappush(a[p], i * 3 ** p)
o = ''
n = len(a)
for i in range(1, n + 1):
	while a[n - i]:
		o += str(heappop(a[n - i])) + ' '
print(o)


from math import gcd
from functools import reduce
from itertools import accumulate
from typing import List
import bisect
import random
from itertools import permutations, combinations
from collections import Counter

def intList(nums: str) -> List[int]:
	return list(map(lambda x: int(x), nums.split(' ')))

def listAll(func, nums: list) -> bool:
	for x in nums:
		if not func(x):
			return False
	return True

def transformStrings(func) -> list:
	return list(map(func, readStrings()))

def getOrNone(iterable, index):
	if 0 <= index < len(iterable):
		return iterable[index]
	return None

def getOrDefault(iterable, index, default):
	if 0 <= index < len(iterable):
		return iterable[index]
	return default

def digitSum(num: int) -> int:
	numString = str(num)
	value = 0
	for x in numString:
		value += int(x)
	return value

def runningReduce(func, nums: list) -> list:
	values = nums.copy()
	for x in range(1, len(nums)):
		values[x] = func(values[x - 1], nums[x])
	return values

def lcm(a, b) -> int:
	return abs(a * b) // gcd(a, b)

def printList(nums: list, end='\n'):
	nums = list(map(lambda x: str(x), nums))
	print(' '.join(nums), end=end)

def readStrings() -> List[str]:
	return input().split(' ')

def readInt() -> int:
	return int(input())

def readInts() -> List[int]:
	return list(map(lambda x: int(x), readStrings()))

def readOtherNumericTypes(func) -> list:
	return list(map(func, readStrings()))

def isEven(num: int) -> bool:
	return num % 2 == 0

def isPositive(num: int) -> bool:
	return num > 0

def isPositiveOrZero(num: int) -> bool:
	return isPositive(num) or num == 0

def digits(num: int) -> int:
	return len(str(num))

def firstDigit(num: int) -> int:
	return int(str(num)[0])

def addToArrayForm(num, k):
	num = list(map(lambda x: str(x), num))
	temp = int(''.join(num))
	number = str(temp + k)
	answer = []
	for x in number:
		answer.append(int(x))
	return answer

def indexFromLast(iterable, value):
	for x in range(len(iterable) - 1, -1, -1):
		if iterable[x] == value:
			return x

def inRange(iterable, index):
	return 0 <= index < len(iterable)

def divisible(num):
	return num % 3 == 0

def rearrange(values: list, currentArrange: list=[]):
	if len(values) == 0:
		printList(currentArrange)
		return
	if len(currentArrange) == 0:
		for x in values:
			if divisible(x):
				if values.__contains__(x // 3):
					temp = values.copy()
					temp.remove(x)
					temp.remove(x // 3)
					v = currentArrange.copy()
					v.append(x)
					v.append(x // 3)
					rearrange(temp, v)
			if values.__contains__(x * 2):
				temp = values.copy()
				temp.remove(x)
				temp.remove(x * 2)
				v = currentArrange.copy()
				v.append(x)
				v.append(x * 2)
				rearrange(temp, v)
	else:
		x = currentArrange[-1]
		if divisible(x):
			if values.__contains__(x // 3):
				temp = values.copy()
				temp.remove(x // 3)
				v = currentArrange.copy()
				v.append(x // 3)
				rearrange(temp, v)
		if values.__contains__(x * 2):
			temp = values.copy()
			temp.remove(x * 2)
			v = currentArrange.copy()
			v.append(x * 2)
			rearrange(temp, v)
input()
nums = readInts()
rearrange(nums)


(n, a) = (int(input()) - 1, list(map(int, input().split())))
for i in a:
	if i % 2 == 1:
		if i * 3 not in a:
			l = i
			break
	elif i * 3 not in a and i // 2 not in a:
		l = i
		break
t = str(l)
while n != 0:
	if l * 2 in a:
		l *= 2
		t += ' ' + str(l)
	elif l // 3 in a:
		l //= 3
		t += ' ' + str(l)
	n -= 1
print(t)


def fact(x):
	r = [0, 0, x]
	while x % 2 == 0:
		x //= 2
		r[0] += 1
	while x % 3 == 0:
		x //= 3
		r[1] -= 1
	return r
input()
d = [fact(int(x)) for x in input().split()]
d.sort()
print(*(x[2] for x in d))


def info(x):
	copy_x = x
	cnt3 = 0
	cnt2 = 0
	while x % 3 == 0:
		x = x // 3
		cnt3 += 1
	while x % 2 == 0:
		x = x // 2
		cnt2 -= 1
	return (cnt3, cnt2, copy_x)
n = int(input())
a = [int(i) for i in input().split()]
new_a = []
for i in a:
	new_a.append(info(i))
new_a.sort()
for i in range(len(new_a) - 1, -1, -1):
	print(new_a[i][2], end=' ')


class SeqNum:

	def __init__(self, number):
		self.num = number
		self.two = 0
		while number % 2 == 0:
			self.two += 1
			number //= 2
		self.three = 0
		while number % 3 == 0:
			self.three += 1
			number //= 3
l = int(input())
seq = [SeqNum(int(x)) for x in input().split()]
min2 = min([x.two for x in seq])
max3 = max([x.three for x in seq])

def pos(x):
	return x.two - min2 + max3 - x.three
print(*[x.num for x in sorted(seq, key=pos)])


n = int(input())
a = list(map(int, input().split()))

def md(x, d):
	res = 0
	dd = 1
	while x % (dd * d) == 0:
		dd *= d
		res += 1
	return res

def cmp(a, b):
	d3a = md(a, 3)
	d2a = md(a, 2)
	d3b = md(b, 3)
	d2b = md(b, 2)
	if d3a == d3b:
		return d2a < d2b
	return d3a > d3b
for i in range(n):
	for j in range(i, n):
		if cmp(a[j], a[i]):
			(a[i], a[j]) = (a[j], a[i])
print(' '.join(map(str, a)))


import math
from decimal import *
import random
from datetime import datetime
import time

def k(n):
	ans = 0
	while n % 3 == 0:
		ans += 1
		n //= 3
	return ans
n = int(input())
arr = list(map(int, input().split()))
ans = []
arr = sorted(arr, key=lambda x: (-k(x), x))
for i in range(n):
	arr[i] = str(arr[i])
print(' '.join(arr))


n = int(input())
a = list(map(int, input().split()))

def calc_deg3(x):
	d = 0
	while x % 3 == 0:
		x //= 3
		d += 1
	return d
m = {}
for ai in a:
	d = calc_deg3(ai)
	if d not in m:
		m[d] = []
	m[d].append(ai)
answer = []
for d in sorted(m.keys(), reverse=True):
	answer.extend(sorted(m[d]))
print(' '.join(map(str, answer)))


def calc(x):
	ret = 0
	while x % 3 == 0:
		x //= 3
		ret += 1
	return ret
n = int(input())
a = sorted([(int(x), calc(int(x))) for x in input().split()], key=lambda x: (-x[1], x[0]))
for elem in a:
	print(elem[0], sep=' ')


def count(num, k):
	if num % k != 0:
		return 0
	return 1 + count(num // k, k)
n = int(input())
a = [*map(int, input().split())]
c = [None] * n
for i in range(0, n):
	c[i] = i
a.sort(key=lambda num: (-count(num, 3), num))
print(' '.join(map(str, a)))


(n, ls, lsf) = (int(input()), list(map(int, input().split(' '))), [])
for l in ls:
	(x, f2, f3) = (l, 0, 0)
	while x % 2 == 0:
		(x, f2) = (x // 2, f2 + 1)
	while x % 3 == 0:
		(x, f3) = (x // 3, f3 + 1)
	lsf.append((f2, f3, l))
lsf.sort(key=lambda z: z[1], reverse=True)
lsf.sort(key=lambda z: z[0])
print(' '.join([str(l[2]) for l in lsf]))


def pow3(x):
	count = 0
	while x % 3 == 0:
		x = x // 3
		count += 1
	return count

def pow2(x):
	count = 0
	while x % 2 == 0:
		x = x // 2
		count += 1
	return count
n = int(input())
l = input().split()
li = [int(i) for i in l]
l = []
for i in li:
	a = pow3(i)
	b = pow2(i)
	l.append((-1 * a, b, i))
l.sort()
for i in l:
	print(i[2], end=' ')


n = int(input())
TC = list(map(int, input().split()))
new = []
for i in range(n):
	for T in TC:
		if T * 2 in TC or (T % 3 == 0 and T // 3 in TC):
			continue
		else:
			new.append(T)
			TC.remove(T)
print(*new[::-1])


n = int(input())
a = [int(i) for i in input().split()]
dupa = []
max = 0
for i in a:
	count = 0
	while i % 3 == 0:
		i //= 3
		count += 1
	dupa.append([i, count])
	if count > max:
		max = count
x3 = []
x2 = []

def sort3(x):
	return x[0]

def sort33(x):
	return x[1]

def sort2(x):
	return x[0]
for i in dupa:
	if i[1] != 0:
		x3.append(i)
	else:
		x2.append(i)
x3 = sorted(x3, key=sort3)
x3 = sorted(x3, key=sort33, reverse=True)
x2 = sorted(x2, key=sort2)
for i in x3 + x2:
	print(i[0] * 3 ** i[1], end=' ')


def maxpower(n):
	if n % 3 != 0:
		return 0
	else:
		count = 0
		while n % 3 == 0:
			n = n // 3
			count += 1
		return count

def mykey(n):
	return (-1 * maxpower(n), n)
n = int(input())
L = list(map(int, input().split()))
print(*sorted(L, key=mykey))


x = []
vis = None

def solve(u):
	vis[u] = 1
	x.append(A[u])
	if len(x) == n:
		return True
	for v in range(n):
		if v != u and (not vis[v]):
			if A[v] == 2 * A[u]:
				if solve(v):
					return True
			if A[u] % 3 == 0 and A[v] == A[u] // 3:
				if solve(v):
					return True
	vis[u] = 0
	x.pop()
	return False
n = int(input())
A = list(map(int, input().split()))
vis = [0 for _ in range(n)]
for i in range(n):
	if solve(i):
		print(' '.join(map(str, x)))
		break


def f(x, n):
	r = 0
	while not x % n:
		x //= n
		r += 1
	return r
n = int(input())
a = map(int, input().split())
print(*sorted(a, key=lambda x: f(x, 2) - f(x, 3)))


n = int(input())
x = [int(y) for y in input().split()]
ans = []
for i in x:
	a = 0
	b = 0
	j = i
	while j % 2 == 0:
		j //= 2
		a += 1
	while j % 3 == 0:
		j //= 3
		b += 1
	ans.append([-b, a, i])
ans.sort()
for z in ans:
	print(z[2], end=' ')


def imprime(arr):
	for i in range(len(arr)):
		print(arr[i]['num'], end=' ')
	print()
	return

def troca(i, j):
	a0 = a[i]
	b0 = b2[i]
	c0 = b3[i]
	a[i] = a[j]
	b2[i] = b2[j]
	b3[i] = b3[j]
	a[j] = a0
	b2[j] = b20
	b3[j] = c0
	return

def pot2(x):
	j = 0
	while x % 2 == 0:
		x = x // 2
		j += 1
	return j

def pot3(x):
	j = 0
	while x % 3 == 0:
		x = x // 3
		j += 1
	return j

def criaDict(x):
	b2 = pot2(x)
	b3 = pot3(x)
	d = {'num': x, 'p2': b2, 'p3': b3}
	return d
n = int(input()) <= 100
a = input().split(' ')
a = map(int, a)
a = list(a)
d = []
for i in range(len(a)):
	d.append(criaDict(a[i]))
d1 = sorted(d, key=lambda k: k['p3'], reverse=True)
d1 = sorted(d1, key=lambda k: k['p2'])
imprime(d1)


def count3(n):
	cnt = 0
	while n % 3 == 0:
		cnt += 1
		n //= 3
	return cnt
n = int(input())
a = list(map(int, input().split()))
for i in range(n):
	a[i] = [count3(a[i]), a[i]]
a.sort(key=lambda x: (-x[0], x[1]))
for x in a:
	print(x[1], end=' ')


from collections import deque
n = int(input())
a = [int(i) for i in input().split()]
b = deque()
b.append(a[0])
a = set(a[1:])
while len(a) > 0:
	if b[-1] % 3 == 0 and b[-1] // 3 in a:
		a.remove(b[-1] // 3)
		b.append(b[-1] // 3)
	elif b[-1] * 2 in a:
		a.remove(b[-1] * 2)
		b.append(b[-1] * 2)
	elif b[0] * 3 in a:
		a.remove(b[0] * 3)
		b.appendleft(b[0] * 3)
	elif b[0] % 2 == 0 and b[0] // 2 in a:
		a.remove(b[0] // 2)
		b.appendleft(b[0] // 2)
	else:
		assert False
s = ''
for b_i in b:
	if len(s) != 0:
		s += ' '
	s += str(b_i)
print(s)


def power(n):
	i = 0
	while n % 2 == 0:
		i += 1
		n = n // 2
	return (-n, i)
m = int(input())
ar = list(map(int, input().split()))
ar.sort(key=power)
print(*ar)


n = int(input())
lst = [int(x) for x in input().split()]
l = -1
for x in range(n):
	if lst[x] % 2 == 0:
		if not lst[x] // 2 in lst and (not lst[x] * 3 in lst):
			l = x
			break
	elif not lst[x] * 3 in lst:
		l = x
		break
if l != -1:
	x = lst[l]
else:
	x = min(lst)
array = []
while n > 0:
	if x % 3 == 0 and x // 3 in lst:
		array.append(x)
		x //= 3
	else:
		array.append(x)
		x *= 2
	n -= 1
print(*array)


import heapq
from collections import Counter

def heuristic(elements, path):
	return len(elements) - len(path)

def is_goal(elements, path):
	return heuristic(elements, path) == 0

def next_steps(elements, path):
	last = path[-1]
	possible_steps = Counter(elements) - Counter(path)
	return [step for (step, count) in possible_steps.items() if last % 3 == 0 and step == last // 3 or step == last * 2]

def a_star(elements):
	closed = set()
	open_stats = []
	open_stats = [(len(elements) - 1, [element]) for element in elements]
	while len(open_stats):
		(h, state) = heapq.heappop(open_stats)
		for next_step in next_steps(elements, state):
			next_state = state + [next_step]
			if is_goal(elements, next_state):
				return next_state
			h_next_state = heuristic(elements, next_state)
			heapq.heappush(open_stats, (h_next_state, next_state))
	return None
n = int(input())
elements = [int(x) for x in input().split()]
print(' '.join((str(x) for x in a_star(elements))))


from collections import defaultdict as dd
n = int(input())
l = [int(i) for i in input().split(' ')]
dm = dd(int)
for i in l:
	dm[i] += 1
for i in range(n):
	d = dm.copy()
	now = l[i]
	p = [now]
	d[now] -= 1
	for j in range(n - 1):
		if d[now // 3] > 0 and now % 3 == 0:
			d[now // 3] -= 1
			p.append(now // 3)
			now = now // 3
		elif d[2 * now] > 0:
			d[2 * now] -= 1
			p.append(2 * now)
			now = 2 * now
		else:
			break
	if len(p) == n:
		break
print(*p)


n = int(input())
m = list(map(int, input().split()))
from collections import Counter
co = Counter(m)
cands = []
for i in m:
	coc = co.copy()
	cand = [i]
	flag = False
	if i % 3 == 0 and coc[i // 3]:
		coc[i // 3] -= 1
		l = i // 3
		cand.append(l)
		flag = True
	elif coc[i * 2]:
		coc[i * 2] -= 1
		l = i * 2
		cand.append(l)
		flag = True
	while flag:
		flag = False
		if l % 3 == 0 and coc[l // 3]:
			coc[l // 3] -= 1
			l = l // 3
			cand.append(l)
			flag = True
		elif coc[l * 2]:
			coc[l * 2] -= 1
			l = l * 2
			cand.append(l)
			flag = True
	cands.append(cand)
for i in cands:
	if len(i) == n:
		print(*i)
		break


n = int(input())
a = list(map(int, input().split()))
b = [0] * len(a)

def search(a, n, num):
	for i in a:
		if i == num:
			return True
	return False
for i in range(n):
	b[0] = a[i]
	check = 0
	for j in range(n - 1):
		if check == 0:
			if b[j] % 3:
				if search(a, n, b[j] * 2):
					b[j + 1] = b[j] * 2
				else:
					check = 1
			elif search(a, n, b[j] // 3):
				b[j + 1] = b[j] // 3
			elif search(a, n, b[j] * 2):
				b[j + 1] = b[j] * 2
			else:
				check = 1
	if check == 0:
		break
for i in b:
	print(i, end=' ')


n = int(input())
lista = list(map(int, input().split()))

def defe(x):
	i = 0
	while x % 2 == 0:
		i += 1
		x /= 2
	return (-x, i)
lista.sort(key=defe)
print(' '.join(list(map(str, lista))))


def play(x, remain):
	if not x in remain:
		return False
	else:
		remain.remove(x)
		anslist.append(str(x))
	if len(remain) == 0:
		return True
	if x % 3 == 0:
		if play(x // 3, remain):
			return True
	if play(x * 2, remain):
		return True
	anslist.remove(str(x))
n = int(input())
a = [int(i) for i in input().split()]
for i in a:
	wk1 = [j for j in a]
	anslist = []
	if play(i, wk1):
		print(' '.join(anslist))
		quit()


n = int(input())
l = list(map(int, input().split()))
p = []
for i in range(n):
	(x, c) = (l[i], 0)
	while l[i] % 3 == 0:
		l[i] = l[i] // 3
		c += 1
	p.append([-c, x])
p.sort()
print(' '.join(list(map(lambda o: str(o[1]), p))))


mod = 1000000007
ii = lambda : int(input())
si = lambda : input()
dgl = lambda : list(map(int, input()))
f = lambda : map(int, input().split())
il = lambda : list(map(int, input().split()))
ls = lambda : list(input())

def dfs(d, sv):
	d[sv] = True
	dfsarr.append(sv)
	for i in d:
		if d[i] == False and (sv * 2 == i or (sv % 3 == 0 and sv // 3 == i)):
			dfs(d, i)
dfsarr = []
n = ii()
l = il()
d = dict()
for i in range(n):
	dfsarr = []
	for j in l:
		d[j] = False
	dfs(d, l[i])
	if all((d[k] for k in d)):
		print(*dfsarr)


x = int(input())
temp_seq = input().split(' ')
seq = [int(temp_seq[i]) for i in range(x)]
final = []
while len(seq) != 0:
	if len(final) == 0:
		final = final + [seq[0]]
		seq.pop(0)
	elif final[0] // 2 in seq:
		final = [final[0] // 2] + final
		seq.remove(final[0])
	elif final[-1] * 2 in seq:
		final = final + [final[-1] * 2]
		seq.remove(final[-1])
	elif final[0] * 3 in seq:
		final = [final[0] * 3] + final
		seq.remove(final[0])
	elif final[-1] % 3 == 0 and final[-1] // 3 in seq:
		final = final + [final[-1] // 3]
		seq.remove(final[-1])
res = ' '.join((str(a) for a in final))
print(res)


n = int(input())
l = list(map(int, input().split()))

def search(partial, current_value, remaining):
	if not partial:
		partial = [current_value]
	if len(remaining) == 0:
		return partial
	res = []
	new_values = [current_value * 2]
	if current_value % 3 == 0:
		new_values.append(current_value // 3)
	for new_value in new_values:
		if new_value in remaining:
			i = remaining.index(new_value)
			for answer in search(partial + [remaining[i]], new_value, remaining[:i] + remaining[i + 1:]):
				if answer:
					res.append(answer)
	return res
for (idx, elem) in enumerate(l):
	ans = search(None, elem, l[:idx] + l[idx + 1:])
	if len(ans) > 0:
		print(' '.join(map(str, ans)))
		break


import sys
from functools import lru_cache, cmp_to_key
from heapq import merge, heapify, heappop, heappush
from math import *
from collections import defaultdict as dd, deque, Counter as C
from itertools import combinations as comb, permutations as perm
from bisect import bisect_left as bl, bisect_right as br, bisect
from time import perf_counter
from fractions import Fraction
mod = int(pow(10, 9) + 7)
mod2 = 998244353

def data():
	return sys.stdin.readline().strip()

def out(*var, end='\n'):
	sys.stdout.write(' '.join(map(str, var)) + end)

def l():
	return list(sp())

def sl():
	return list(ssp())

def sp():
	return map(int, data().split())

def ssp():
	return map(str, data().split())

def l1d(n, val=0):
	return [val for i in range(n)]

def l2d(n, m, val=0):
	return [l1d(n, val) for j in range(m)]

def build(C, B):
	if len(B) == len(C):
		return B
	if 2 * B[-1] in C and B.count(2 * B[-1]) < C.count(2 * B[-1]):
		x = build(C, B + [2 * B[-1]])
		if len(x) == len(C):
			return x
	if B[-1] % 3 == 0 and B[-1] // 3 in C and (B.count(B[-1] // 3) < C.count(B[-1] // 3)):
		x = build(C, B + [B[-1] // 3])
		if len(x) == len(C):
			return x
	return B
n = l()[0]
A = l()
B = []
C = A[:]
for i in range(n):
	x = build(C, [A[i]])
	if len(x) == n:
		break
print(*x)


import sys
input = sys.stdin.readline

def func(n):
	r = 0
	while n % 2 == 0:
		n = n // 2
		r += 1
	while n % 3 == 0:
		n //= 3
		r -= 1
	return r
q = int(input())
a = list(map(int, input().split()))
print(*sorted(a, key=func))


n = int(input())
a = [int(i) for i in input().split()]
after = {}
f = -1
for i in range(n):
	if a[i] % 2 == 0 and a[i] // 2 in a:
		after[a[i] // 2] = a[i]
	elif a[i] * 3 in a:
		after[a[i] * 3] = a[i]
	else:
		f = a[i]
for i in range(n):
	print(f, end=' ')
	if i != n - 1:
		f = after[f]


n = int(input())
a = input().split()
ls = [[] for i in range(50)]
for i in range(n):
	a[i] = int(a[i])
	x = a[i]
	count = 0
	while x % 3 == 0:
		x = x // 3
		count += 1
	ls[count].append(a[i])
for i in range(50):
	ls[50 - i - 1].sort()
	for j in range(len(ls[50 - i - 1])):
		print(ls[50 - i - 1][j], end=' ')


n = int(input())
a = list(map(int, input().split(' ')))
ar = []

def dfs(n):
	if n % 3 == 0 and n // 3 in a:
		ar.append(n // 3)
		dfs(n // 3)
	elif n * 2 in a:
		ar.append(n * 2)
		dfs(n * 2)
for i in range(0, len(a)):
	dfs(a[i])
	if len(ar) == len(a) - 1:
		ar.insert(0, a[i])
		break
	del ar[:]
for i in range(0, len(ar)):
	print(ar[i], end=' ')


amount = int(input())
array = [int(s) for s in input().split()]
pairs = []
for i in range(len(array)):
	tmp = array[i]
	counter = 0
	while not tmp % 3:
		counter += 1
		tmp = tmp // 3
	pairs.append((-counter, array[i]))
pairs = sorted(pairs)
print(' '.join((str(pairs[i][1]) for i in range(len(pairs)))))


def dfs(u, a, visited, path):
	path.append(u)
	if len(path) == len(a):
		return True
	vlist = [u * 2] if u % 3 != 0 else [u * 2, u // 3]
	for v in vlist:
		if v in a and v not in visited:
			visited.add(v)
			if dfs(v, a, visited, path):
				return True
			visited.remove(v)
	path.pop()
	return False

def solve(a):
	a = set(a)
	for x in a:
		path = []
		visited = set()
		if dfs(x, a, visited, path):
			return path
	assert 0

def main():
	n = int(input())
	a = [int(_) for _ in input().split()]
	assert len(a) == n
	ans = solve(a)
	print(' '.join(map(str, ans)))
main()


def main():
	n = int(input())
	ar = list(map(int, input().split()))
	lookup = {ar[i]: i for i in range(n)}

	def dfs(idx, ai, p):
		visited[idx] = True
		ans[ai] = ar[idx]
		if ai + 1 == n:
			return True
		res = False
		if ar[idx] % 3 == 0:
			t = ar[idx] // 3
			if t in lookup and t != p and (not visited[lookup[t]]):
				res = res or dfs(lookup[t], ai + 1, ar[idx])
				if res:
					return True
		t = ar[idx] * 2
		if t in lookup and t != p and (not visited[lookup[t]]):
			res = res or dfs(lookup[t], ai + 1, ar[idx])
			if res:
				return True
		return False
	for i in range(n):
		visited = [False] * n
		ans = [0] * n
		if dfs(i, 0, -1):
			print(*ans)
			break
main()


n = int(input())
a = list(map(int, input().split()))

def d3(c):
	ans = 0
	while c % 3 == 0:
		c //= 3
		ans += 1
	return ans
a = [(d3(i), i) for i in a]
a = sorted(a, key=lambda x: (-x[0], x[1]))
print(' '.join([str(i[1]) for i in a]))


n = int(input())
a = list(map(int, input().split()))
g = [[0 for i in range(n)] for j in range(n)]
for i in range(n):
	for j in range(n):
		if i == j:
			continue
		if a[i] == 2 * a[j] or 3 * a[i] == a[j]:
			g[j][i] = 1
		if a[j] == 2 * a[i] or 3 * a[j] == a[i]:
			g[i][j] = 1
INF = 100000
pwd = [[INF for i in range(n)] for j in range(n)]
nxt = [[-1 for i in range(n)] for j in range(n)]
for i in range(n):
	for j in range(n):
		if g[i][j] == 1:
			pwd[i][j] = -1
			nxt[i][j] = j
for k in range(n):
	for i in range(n):
		for j in range(n):
			if pwd[i][k] < INF and pwd[k][j] < INF:
				pwd[i][j] = min(pwd[i][j], pwd[i][k] + pwd[k][j])
				nxt[i][j] = nxt[i][k]
u = 0
v = 0
for i in range(n):
	for j in range(n):
		if pwd[i][j] == -n + 1:
			u = i
			v = j
path = list()
while u != v:
	path.append(a[u])
	u = nxt[u][v]
path.append(a[v])
print(' '.join([str(x) for x in path]))


import sys
input = lambda : sys.stdin.readline().rstrip('\r\n')

def solve():
	n = int(input())
	a = list(map(int, input().split()))
	b = a[:]
	t = [[0, 0] for i in range(n)]
	for i in range(n):
		while a[i] % 3 == 0:
			t[i][0] += 1
			a[i] //= 3
		while a[i] % 2 == 0:
			t[i][1] += 1
			a[i] //= 2
		t[i].append(i)
	t.sort(key=lambda i: i[0], reverse=1)
	t.sort(key=lambda i: i[1])
	for i in t:
		print(b[i[2]], end=' ')
	print()
solve()


import sys, os
from math import sqrt, gcd, ceil, log, floor
from bisect import bisect, bisect_left
from collections import defaultdict, Counter, deque
from heapq import heapify, heappush, heappop
input = sys.stdin.readline
read = lambda : list(map(int, input().strip().split()))
MOD = 10 ** 9 + 7

def main():
	n = int(input())
	arr = read()
	curr = arr[0]
	i = 0
	while True:
		if curr * 3 in arr:
			curr *= 3
		elif curr % 2 == 0 and curr // 2 in arr:
			curr //= 2
		else:
			break
		i += 1
		if i > 100:
			break
	ans = []
	i = 0
	while True:
		ans.append(curr)
		if curr % 3 == 0 and curr // 3 in arr:
			curr //= 3
		elif curr * 2 in arr:
			curr *= 2
		else:
			break
		i += 1
		if i > 100:
			break
	print(*ans)
main()


num = int(input())
Result = []
List = []
String = input().split(' ')
for i in String:
	List.append(int(i))
for i in List:
	if i * 2 in List or (i % 3 == 0 and i // 3 in List):
		Result.append(i)
		for j in Result:
			if j * 2 in List:
				Result.append(j * 2)
			if j % 3 == 0 and j // 3 in List:
				Result.append(j // 3)
	if len(Result) != num:
		Result.clear()
	else:
		break
for i in Result:
	print(i)


n = int(input())
l = list(map(int, input().split()))
d = {}
for t in l:
	if t not in d:
		d[t] = 1
	else:
		d[t] += 1
k = [l[0]]
x = l[0]
d[x] -= 1
for t in range(100):
	if x * 2 in d and d[x * 2] > 0:
		k.append(x * 2)
		d[x * 2] -= 1
		x *= 2
	elif x % 3 == 0 and x // 3 in d and (d[x // 3] > 0):
		k.append(x // 3)
		d[x // 3] -= 1
		x = x // 3
x = l[0]
for t in range(100):
	if x % 2 == 0 and x // 2 in d and (d[x // 2] > 0):
		k.insert(0, x // 2)
		d[x // 2] -= 1
		x = x // 2
	elif x * 3 in d and d[x * 3] > 0:
		k.insert(0, x * 3)
		d[x * 3] -= 1
		x = x * 3
print(*k)


n = int(input())
s = input()
a = [int(x) for x in s.strip().split(' ')]
d = []
for x in a:
	d.append(x * 2)
	if x % 3 == 0:
		d.append(x // 3)
ans = []
head = -1
for i in range(n):
	if a[i] not in d:
		head = i
		break
ans.append(a[head])
h = a[head]
for i in range(1, n):
	if h % 3 == 0:
		x = h // 3
		if x in a:
			ans.append(x)
			h = x
			continue
	x = h * 2
	if x in a:
		ans.append(x)
		h = x
ansn = len(ans)
for i in range(ansn):
	print(ans[i], end=' ')
print('')


def poly_check(nums):
	for i in range(len(nums) - 1):
		if nums[i + 1] // 2 != nums[i] and nums[i + 1] * 3 != nums[i]:
			return False
	return True

def rec_poly(fr, to):
	if len(fr) == 0:
		if poly_check(to):
			for n in to:
				print(n, end=' ')
	first = to[0]
	if first * 3 in fr or first // 2 in fr:
		if first * 3 in fr:
			to.insert(0, first * 3)
			fr.remove(first * 3)
			rec_poly(fr[:], to[:])
		if first // 2 in fr:
			to.insert(0, first // 2)
			fr.remove(first // 2)
			rec_poly(fr[:], to[:])
	else:
		return
n = int(input())
ns = list(map(int, input().split()))
ps = []
not3 = sorted([n for n in ns if n % 3 != 0])
for n in not3:
	ps.append(n)
	ns.remove(n)
if ps:
	rec_poly(ns[:], ps[:])
else:
	for n in ns:
		nns = ns[:]
		pps = ps[:]
		nns.remove(n)
		pps.append(n)
		rec_poly(nns, pps)


n = int(input())
lst = [int(i) for i in input().split()]
pairs = list()
for i in range(len(lst)):
	(temp, count) = (lst[i], 0)
	while not temp % 3:
		count += 1
		temp //= 3
	pairs.append((-count, lst[i]))
pairs.sort()
print(' '.join((str(pairs[i][1]) for i in range(len(pairs)))))


input()
numbers = set(map(int, input().split()))
result = []
for n in numbers:
	if n * 2 not in numbers and (n % 3 != 0 or n // 3 not in numbers):
		result.append(n)
		numbers.remove(n)
		break
while numbers:
	if result[0] % 2 == 0:
		candidate = result[0] // 2
		if candidate in numbers:
			numbers.remove(candidate)
			result.insert(0, candidate)
			continue
	candidate = result[0] * 3
	if candidate in numbers:
		numbers.remove(candidate)
		result.insert(0, candidate)
print(' '.join((str(x) for x in result)))


n = int(input())
s = list(map(int, input().split()))
ans = []
for i in s:
	n = i
	c2 = c3 = 0
	while i % 2 == 0:
		i //= 2
		c2 += 1
	while i % 3 == 0:
		i //= 3
		c3 += 1
	ans.append([-c3, c2, n])
ans.sort()
for i in ans:
	print(i[2], end=' ')


def dfs(v, a, c, t):
	c[v] = 1
	for nb in adj[v]:
		if not c[nb]:
			dfs(nb, a, c, t)
	t.append(v)
(n, a) = (int(input()), list(map(int, input().split())))
adj = [[] for _ in range(n)]
for i in range(n - 1):
	for j in range(i + 1, n):
		if a[i] * 2 == a[j] or a[j] * 3 == a[i]:
			adj[i].append(j)
		elif a[j] * 2 == a[i] or a[i] * 3 == a[j]:
			adj[j].append(i)
t = []
c = [0] * n
for i in range(n):
	if c[i] == 0:
		dfs(i, adj, c, t)
print(' '.join([str(a[i]) for i in t[::-1]]))


def isThird(x, y):
	return x == y * 3

def isDouble(x, y):
	return x == y / 2

def sort(lista):
	if len(lista) == 0:
		return []
	lista = sorted(lista)
	result = []
	n = len(lista)
	result.append(lista.pop(0))
	p = -1
	while len(result) < n:
		p = (p + 1) % len(lista)
		if lista[p] == result[0] * 3 or lista[p] == result[0] / 2:
			result.insert(0, lista.pop(p))
		elif lista[p] == result[-1] * 2 or lista[p] == result[-1] / 3:
			result.append(lista.pop(p))
	return result

def main():
	n = int(input())
	numeros = input().split()
	numeros = [int(x) for x in numeros]
	mult6 = []
	mult3 = []
	mult2 = []
	none = []
	for num in numeros:
		if num % 6 == 0:
			mult6.append(num)
		elif num % 2 == 0:
			mult2.append(num)
		elif num % 3 == 0:
			mult3.append(num)
		else:
			none.append(num)
	mult3 = sorted(mult3, reverse=True)
	mult6 = sort(mult6)
	mult2 = sorted(mult2)
	final = mult3 + mult6 + none + mult2
	for num in final:
		print(num, end=' ')
	print()
main()


def get(x):
	a = x
	cnt = [0] * 2
	for d in (2, 3):
		while x % d == 0:
			cnt[d - 2] += 1
			x //= d
	return (cnt[0], -cnt[1], a)
(n,) = map(int, input().split())
a = list(map(int, input().split()))
values = sorted([get(x) for x in a])
print(*[x[2] for x in values])


n = int(input())
a = list(map(int, input().split()))
d = dict()
minP = 9999
maxP = 0
for x in a:
	curr = x
	p = 0
	while curr % 3 == 0:
		curr //= 3
		p += 1
	minP = min(minP, p)
	maxP = max(maxP, p)
	l = d.get(p, [])
	l.append(x)
	d[p] = l
for key in range(maxP, minP - 1, -1):
	l = d[key]
	l.sort()
	if key > minP:
		e = ' '
	else:
		e = ''
	print(' '.join(map(str, l)), sep=' ', end=e)


import math
n = int(input())
a = list(map(int, input().split()))
r = []
for i in range(n):
	x = a[i]
	t3 = 0
	t2 = 0
	r.append([a[i]])
	while x % 3 == 0 or x % 2 == 0:
		if x % 3 == 0:
			x //= 3
			t3 += 1
		else:
			x //= 2
			t2 += 1
	r[-1] += [t3, t2]
r.sort(key=lambda x: (-x[1], x[2]))
for i in range(n):
	print(r[i][0], end=' ')


def func(a):
	b = a
	(c, d) = (0, 0)
	while a % 3 == 0:
		a = a // 3
		c = c + 1
	while b % 2 == 0:
		b = b // 2
		d = d + 1
	if d == 0:
		return c + 2
	return c + 1 / d
n = int(input())
a = list(map(int, input().strip().split()))
b = []
for i in range(n):
	b.append([func(a[i]), a[i]])
b.sort(reverse=True)
c = []
for i in range(n):
	c.append(b[i][1])
print(*c)


def three_pow(a):
	i = 0
	while a % 3 ** (i + 1) == 0:
		i += 1
	return i
n = int(input())
A = [int(x) for x in input().split()]
A.sort(key=lambda x: (-three_pow(x), x))
print(' '.join(map(str, A)))


def f(n, A):
	A = list(map(int, A.split()))
	dct = [[0, 0, 0] for i in range(n)]
	for i in range(n):
		tmp = A[i]
		while True:
			if tmp % 3 == 0:
				dct[i][0] += 1
				tmp //= 3
			elif tmp % 2 == 0:
				dct[i][1] -= 1
				tmp //= 2
			else:
				break
		dct[i][2] = i
	dct.sort(reverse=True)
	res = []
	for i in range(n):
		res += [str(A[dct[i][2]])]
	return ' '.join(res)
a = int(input())
A = input()
print(f(a, A))


n = int(input())
m = list(map(int, input().split(' ')))
l = [[0 for i in range(n)] for i in range(n)]
d = dict()
for i in range(n):
	d[m[i]] = i
for i in range(n):
	if m[i] * 2 in m:
		l[i][d[m[i] * 2]] = 1
	if not m[i] % 3 and m[i] // 3 in m:
		l[i][d[m[i] // 3]] = 1
z = []
for i in range(n):
	if not any(l[i]):
		x = i
		z.append(i)
		break
k = n - 1
while k:
	for i in range(n):
		if l[i][x]:
			x = i
			z.append(i)
			k -= 1
			break
z.reverse()
for i in z:
	print(m[i], end=' ')


def pow3(x):
	ans = 0
	while x % 3 == 0:
		x = x // 3
		ans += 1
	return ans
n = int(input())
a = list(map(int, input().split()))
for i in range(n):
	a[i] = [-1 * pow3(a[i]), a[i]]
a.sort()
for i in range(n):
	a[i] = a[i][1]
print(*a)


input()
arr = list(map(int, input().split()))

def getscale(n):
	while n % 3 == 0:
		n //= 3
	while n % 2 == 0:
		n //= 2
	return n
scale = getscale(arr[0])

def coord(n):
	(x, y) = (0, 0)
	while n % 3 == 0:
		n //= 3
		y += 1
	while n % 2 == 0:
		n //= 2
		x += 1
	return (x, -y)
arr = list(map(coord, arr))
arr.sort()

def construct(n):
	return 2 ** n[0] * 3 ** (-n[1])
print(' '.join(map(lambda e: str(construct(e) * scale), arr)))


from sys import stdin, stdout
from collections import deque
st = lambda : list(stdin.readline().strip())
li = lambda : list(map(int, stdin.readline().split()))
mp = lambda : map(int, stdin.readline().split())
inp = lambda : int(stdin.readline())
pr = lambda n: stdout.write(str(n) + '\n')
mod = 1000000007

def solve():
	n = inp()
	l = li()
	d = {i: [] for i in l}
	m = max(d)
	for i in range(n):
		if 2 * l[i] <= m:
			if 2 * l[i] in l:
				d[l[i]].append(2 * l[i])
		if l[i] % 3 == 0:
			if l[i] // 3 in l:
				d[l[i]].append(l[i] // 3)
	for i in l:
		q = deque()
		v = set()
		par = {i: -1 for i in l}
		q.append(i)
		ans = [i]
		v.add(i)
		while q:
			a = q.popleft()
			for i in d[a]:
				par[i] = a
				q.append(i)
		if list(par.values()).count(-1) == 1:
			dd = {}
			for i in par:
				dd[par[i]] = i
			x = dd[-1]
			print(x, end=' ')
			for i in range(n - 1):
				print(dd[x], end=' ')
				x = dd[x]
for _ in range(1):
	solve()


import sys
input = sys.stdin.readline
n = int(input())
a = list(map(int, input().split()))
b = []
o = [[] for i in range(80)]
for i in a:
	temp = int(str(i))
	c = 0
	while True:
		if temp % 2 == 0:
			temp /= 2
			c += 1
		else:
			break
	o[c].append(i)
f = []
for i in o:
	f = f + sorted(i)[::-1]
print(*f)


def find(ready, rest, restcount):
	if restcount == 0:
		return ready
	if ready[0] * 3 in rest.keys() and rest[ready[0] * 3] > 0:
		rest1 = dict(rest)
		rest1[ready[0] * 3] -= 1
		res = find([ready[0] * 3] + ready, rest1, restcount - 1)
		if res:
			return res
	if ready[0] // 2 in rest.keys() and rest[ready[0] // 2] > 0:
		rest1 = dict(rest)
		rest1[ready[0] // 2] -= 1
		res = find([ready[0] // 2] + ready, rest1, restcount - 1)
		if res:
			return res
	if ready[-1] // 3 in rest.keys() and rest[ready[-1] // 3] > 0:
		rest1 = dict(rest)
		rest1[ready[-1] // 3] -= 1
		res = find(ready + [ready[-1] // 3], rest1, restcount - 1)
		if res:
			return res
	if ready[-1] * 2 in rest.keys() and rest[ready[-1] * 2] > 0:
		rest1 = dict(rest)
		rest1[ready[-1] * 2] -= 1
		res = find(ready + [ready[-1] * 2], rest1, restcount - 1)
		if res:
			return res
	return False
n = int(input())
a = [int(x) for x in input().split()]
b = {}
for e in a:
	if e in b.keys():
		b[e] += 1
	else:
		b[e] = 1
b[a[0]] -= 1
print(' '.join(map(str, find([a[0]], b, n - 1))))


import sys
sys.setrecursionlimit(10 ** 6)
debug_mode = True if len(sys.argv) > 1 and sys.argv[1] == '-d' else False
if debug_mode:
	import os
	infile = open(os.path.abspath(__file__).replace('.py', '.in'))

	def input():
		return infile.readline()

def main():
	n = int(input().strip())
	A = list(map(int, input().strip().split()))
	sA = set(A)
	last = None
	for a in A:
		if a * 2 not in sA and (a % 3 == 0 and a // 3 not in sA or a % 3 != 0):
			last = a
			break
	(curr, res, cnt) = (last, [last], 1)
	while cnt < n:
		if curr % 2 == 0 and curr // 2 in sA:
			curr = curr // 2
		elif curr * 3 in sA:
			curr = curr * 3
		res.append(curr)
		cnt += 1
	res.reverse()
	print(' '.join(map(str, res)))
main()
if debug_mode:
	infile.close()


def div(a, l):
	if a % 3 == 0:
		x = a // 3
	else:
		return False
	if x in l:
		return True
	else:
		return False

def mul(a, l):
	x = a * 2
	if x in l:
		return True
	else:
		return False
n = int(input())
l = list(map(int, input().split()))
for i in l:
	p = []
	p.extend(l)
	ans = []
	ans.append(i)
	p.remove(i)
	start = i
	flag = 0
	while len(p) != 0:
		if div(start, p):
			ans.append(start // 3)
			p.remove(start // 3)
			start = start // 3
		elif mul(start, p):
			ans.append(start * 2)
			p.remove(start * 2)
			start = start * 2
		else:
			break
	if len(ans) == n:
		flag = 1
		break
print(*ans)


n = int(input())
data = map(int, input().split())
mass = []
for el in data:
	save = el
	th_deg = 0
	tw_deg = 0
	while el % 3 == 0:
		el //= 3
		th_deg += 1
	while el % 2 == 0:
		el //= 2
		tw_deg += 1
	mass.append((save, tw_deg, th_deg))

def comp(a, b):
	if a[2] > b[2]:
		return False
	if a[2] < b[2]:
		return True
	return not a[1] < b[1]
for i in range(n):
	for j in range(i + 1, n):
		if comp(mass[i], mass[j]):
			(mass[i], mass[j]) = (mass[j], mass[i])
for el in mass:
	print(el[0], end=' ')


def rec(x, fArr, secArr):
	fArr.remove(x)
	secArr.append(x)
	if 2 * x in fArr:
		return rec(2 * x, fArr, secArr)
	elif x % 3 == 0 and x // 3 in fArr:
		return rec(x // 3, fArr, secArr)
	elif len(fArr) == 0:
		return secArr
	else:
		return []
n = int(input())
a = list(map(int, input().split()))
b = []
for i in range(n):
	b = rec(a[i], a.copy(), [])
	if b != []:
		break
print(*b)


n = int(input())
mas = input().split()
s = set()
for (i, x) in enumerate(mas):
	mas[i] = int(x)
	s.add(mas[i])
start = -1
for x in mas:
	if not (x % 2 == 0 and x // 2 in s or x * 3 in s):
		start = x
		break
i = 1
ans = [start]
while i < n:
	if start * 2 in s:
		ans.append(start * 2)
		start = start * 2
		i += 1
	else:
		ans.append(start // 3)
		start = start // 3
		i += 1
print(' '.join((str(i) for i in ans)))


def graph(arr, n):
	ret = [-1] * n
	for i in range(n):
		for j in range(n):
			if i == j:
				continue
			if 2 * arr[i] == arr[j]:
				ret[i] = arr[j]
			elif arr[i] == 3 * arr[j]:
				ret[i] = arr[j]
	return ret

def dfs(graph, arr):
	result = []
	while len(graph) != 0:
		for i in range(len(graph)):
			if graph[i] == -1:
				result.append(arr[i])
				for j in range(len(graph)):
					if graph[j] == arr[i]:
						graph[j] = -1
				del arr[i]
				del graph[i]
				break
	result.reverse()
	for item in result:
		print(item, end=' ')
	print()

def main():
	n = int(input())
	arr = [int(t) for t in input().split(' ')]
	dfs(graph(arr, n), arr)
main()


input()
v = list(map(int, input().split()))

def find_last_position(li):
	li = []
	for i in v:
		if i % 3 == 0 and i // 3 in v:
			li.append(i)
		elif i * 2 in v:
			li.append(i)
	for i in v:
		if i not in li:
			return i

def find_path(li):
	v_new = []
	e = find_last_position(li)
	v_new.append(e)
	li.remove(e)
	while True:
		if e * 3 in li:
			e = e * 3
			v_new.append(e)
			li.remove(e)
		elif e >> 1 in li:
			e = e >> 1
			v_new.append(e)
			li.remove(e)
		else:
			break
	return v_new
for i in reversed(find_path(v)):
	print(i, end=' ')


from collections import deque
input()
a = sorted(map(int, input().split()))
z = deque([a[0]])
while len(a) != len(z):
	if z[0] * 3 in a:
		z.appendleft(z[0] * 3)
	if z[-1] * 2 in a:
		z.append(z[-1] * 2)
	if z[0] % 2 == 0 and z[0] // 2 in a:
		z.appendleft(z[0] // 2)
	if z[-1] % 3 == 0 and z[-1] // 3 in a:
		z.append(z[-1] // 3)
print(*z)


n = int(input())
arr = [(int(x), int(x)) for x in input().strip().split()]
ans = []
while len(ans) < n:
	odds = []
	evens = []
	for (x, y) in arr:
		if y % 2 == 1:
			odds.append((x, y))
		else:
			evens.append((x, y // 2))
	ans += [x for (x, y) in sorted(odds, key=lambda x: x[0], reverse=True)]
	arr = evens
print(' '.join([str(x) for x in ans]))


n = int(input())
A = list(map(int, input().split()))
mul2 = [0] * n
div3 = [0] * n
for i in range(n):
	if A[i] * 2 in A:
		mul2[i] = 1
	if A[i] % 3 == 0 and A[i] // 3 in A:
		div3[i] = 1
index = -1
for i in range(n):
	if mul2[i] == 0 and div3[i] == 0:
		index = i
		break
ans = [0] * n
visited = [0] * n
visited[index] = 1
ans[n - 1] = A[index]
for i in range(n - 2, -1, -1):
	if ans[i + 1] * 3 in A and visited[A.index(ans[i + 1] * 3)] == 0:
		ans[i] = ans[i + 1] * 3
	elif ans[i + 1] // 2 in A and visited[A.index(ans[i + 1] // 2)] == 0:
		ans[i] = ans[i + 1] // 2
for i in range(n):
	print(ans[i], end=' ')


print(*sorted(list(map(int, __import__('sys').stdin.read().split('\n')[1].split())), key=lambda x: ((lambda f, x, y: f(f, x, y))(lambda f, x, y: 0 if x == 0 or x % y != 0 else f(f, x // y, y) + 1, x, 2), -(lambda f, x, y: f(f, x, y))(lambda f, x, y: 0 if x == 0 or x % y != 0 else f(f, x // y, y) + 1, x, 3))))


def tri(a):
	k = 0
	while a % 3 == 0:
		k += 1
		a //= 3
	return k
n = input()
katya = list(map(int, input().split()))
l = [(-tri(x), x) for x in katya]
p = [x[1] for x in sorted(l)]
print(*p)


n = int(input())
array = [int(i) for i in input().split()]
s = set()
for i in array:
	s.add(i)
z = [0] * 300
i = 150
j = 151
x = array[0]
y = array[0]
z[i] = x
i -= 1
s.remove(x)
while len(s) != 0:
	if x * 3 in s:
		z[i] = int(x * 3)
		s.remove(x * 3)
		x = x * 3
		i -= 1
	if x // 2 in s and x % 2 == 0:
		z[i] = int(x // 2)
		s.remove(x // 2)
		x = x // 2
		i -= 1
	if y // 3 in s and y % 3 == 0:
		z[j] = int(y // 3)
		s.remove(y // 3)
		y = y // 3
		j += 1
	if y * 2 in s:
		z[j] = int(y * 2)
		s.remove(y * 2)
		y = y * 2
		j += 1
for i in z:
	if i != 0:
		print(i, end=' ')


n = int(input())
values = input()
values = values.split()
factor = [[]] * 101
for i in range(n):
	number = int(values[i])
	factor[i] = [number, 0]
	temp_number = number
	while temp_number % 3 == 0:
		factor[i][1] += 1
		temp_number //= 3
maximo = 0
curr_max = -1
str_ans = ''
j = 0
while j < n:
	for i in range(n):
		if factor[i][1] > maximo:
			maximo = factor[i][1]
			curr_max = int(factor[i][0])
	if curr_max != -1:
		arr_curr = [curr_max]
	else:
		arr_curr = []
	for m in range(n):
		if factor[m][1] == maximo and curr_max != int(factor[m][0]):
			arr_curr.append(int(factor[m][0]))
			j += 1
	arr_curr = sorted(arr_curr)
	for k in range(len(arr_curr)):
		str_ans += str(arr_curr[k]) + ' '
		for l in range(n):
			if factor[l][0] == arr_curr[k]:
				factor[l][1] = -1
	maximo = 0
	curr_max = -1
	j += 1
print(str_ans)


from collections import defaultdict
n = int(input())
l = list(map(int, input().split()))
d = defaultdict(list)

def DFS(x, d, l):
	visited = set()
	stack = [x]
	while len(stack):
		temp = stack.pop()
		if temp in l:
			print(temp, end=' ')
		visited.add(temp)
		for j in d[temp]:
			if j in visited:
				continue
			stack.append(j)
for i in l:
	d[i].append(2 * i)
	if not i % 3:
		d[i].append(i // 3)
for j in l:
	flag = 0
	for k in l:
		if j in d[k]:
			flag = 1
			break
	if flag == 0:
		break
DFS(j, d, l)


import sys
from collections import defaultdict
input = sys.stdin.readline

def main():
	n = int(input())
	a = list(map(int, input().split()))
	for x in a:
		d = defaultdict(lambda : 0)
		for y in a:
			d[y] += 1
		bad = False
		ans = [x]
		for _ in range(n - 1):
			if d[2 * x] > 0:
				d[2 * x] -= 1
				x *= 2
			elif x % 3 == 0 and d[x // 3] > 0:
				d[x // 3] -= 1
				x //= 3
			else:
				bad = True
				break
			ans.append(x)
		if not bad:
			print(' '.join(map(str, ans)))
			return
	assert 0
main()


n = int(input())
a = list(map(int, input().split()))
ok = False
a.sort()

def search(t):
	l = 0
	r = n - 1
	while r - l >= 0:
		mid = (r + l) // 2
		if a[mid] == t:
			return mid
		if t < a[mid]:
			r = mid - 1
		if t > a[mid]:
			l = mid + 1
	return -1
if n == 1:
	print(a[0])
else:
	for i in range(n):
		q = [[[a[i]], [0] * n]]
		while q:
			e = q.pop()
			ne = e[0]
			v = e[1]
			v[i] = 1
			if len(ne) == n:
				print(' '.join(map(str, ne)))
				ok = True
				break
			if ne[-1] % 3 == 0 and search(ne[-1] // 3) >= 0 and (v[search(ne[-1] // 3)] == 0):
				nv = v.copy()
				nv[search(ne[-1] // 3)] = 1
				q.append([ne + [ne[-1] // 3], nv])
			if search(ne[-1] * 2) >= 0 and v[search(ne[-1] * 2)] == 0:
				nv = v.copy()
				nv[search(ne[-1] * 2)] = 1
				q.append([ne + [ne[-1] * 2], nv])
		if ok:
			break


tempdict = dict()
input()
for i in input().split():
	i = int(i)
	tempdict[i] = True
key = i
ans = str(key)
while True:
	if key % 2 is 0 and tempdict.get(key // 2):
		key = key // 2
		ans = str(key) + ' ' + ans
		continue
	if tempdict.get(key * 3):
		key = key * 3
		ans = str(key) + ' ' + ans
		continue
	break
key = i
while True:
	if key % 3 is 0 and tempdict.get(key // 3):
		key = key // 3
		ans = ans + ' ' + str(key)
		continue
	if tempdict.get(key * 2):
		key = key * 2
		ans = ans + ' ' + str(key)
		continue
	break
print(ans)


from math import sqrt

def Euclidus(elem):
	return sqrt(elem[0] ** 2 + elem[1] ** 2)

def Decart(elem):
	number = elem
	answer = [100, 0, 0]
	answer[2] = elem
	while number % 3 == 0 and number != 0:
		number //= 3
		answer[0] -= 1
	while number % 2 == 0 and number != 0:
		number //= 2
		answer[1] += 1
	return answer

def comp(elem):
	return Euclidus(elem)
n = int(input())
s = [int(i) for i in input().split()]
for i in range(len(s)):
	s[i] = Decart(s[i])
s.sort(key=comp)
for elem in s:
	print(elem[2], end=' ')


n = int(input())
numbers = list(map(int, input().split(' ')))
divide_by_three = {}
for i in numbers:
	j = 0
	while i % 3 ** j == 0:
		j += 1
	divide_by_three[i] = j
num = [(-v, k) for (k, v) in divide_by_three.items()]
num = sorted(num)
print(*[i[1] for i in num])


import math, string, itertools, fractions, heapq, collections, re, array, bisect, sys, copy, functools
inf = 10 ** 20
eps = 1.0 / 10 ** 10
mod = 10 ** 9 + 7
mod2 = 998244353
dd = [(-1, 0), (0, 1), (1, 0), (0, -1)]
ddn = [(-1, 0), (-1, 1), (0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1)]

def LI():
	return list(map(int, sys.stdin.readline().split()))

def LLI():
	return [list(map(int, l.split())) for l in sys.stdin.readlines()]

def LI_():
	return [int(x) - 1 for x in sys.stdin.readline().split()]

def LF():
	return [float(x) for x in sys.stdin.readline().split()]

def LS():
	return sys.stdin.readline().split()

def I():
	return int(sys.stdin.readline())

def F():
	return float(sys.stdin.readline())

def S():
	return input()

def pf(s):
	return print(s, flush=True)

def pe(s):
	return print(str(s), file=sys.stderr)

def JA(a, sep):
	return sep.join(map(str, a))

def JAA(a, s, t):
	return s.join((t.join(map(str, b)) for b in a))

def IF(c, t, f):
	return t if c else f

def YES(c):
	return IF(c, 'YES', 'NO')

def Yes(c):
	return IF(c, 'Yes', 'No')

def main():
	t = 1
	rr = []
	for _ in range(t):
		n = I()
		a = LI()
		t = collections.defaultdict(list)
		for c in a:
			k = 0
			u = c
			while u % 3 == 0:
				k += 1
				u //= 3
			t[k].append(c)
		r = []
		for (k, v) in sorted(t.items(), reverse=True):
			r.extend(sorted(v))
		rr.append(JA(r, ' '))
	return JA(rr, '\n')
print(main())


n = int(input())
a = list(map(int, input().split()))
b = [0 for i in range(105)]
ok = False

def dfs(now, ans):
	global ok
	global b
	if ans == n:
		ok = True
		b[ans] = now
		return
	if now % 3 == 0 and now // 3 in a:
		dfs(now // 3, ans + 1)
	if ok:
		b[ans] = now
		return
	if now * 2 in a:
		dfs(now * 2, ans + 1)
	if ok:
		b[ans] = now
		return
	return
for i in range(n):
	dfs(a[i], 1)
	if ok:
		break
for i in range(n - 1):
	print(b[i + 1], end=' ')
print(b[n])


from collections import defaultdict
N = int(input())
a = list(map(int, input().split()))
dic = defaultdict(int)
for i in range(N):
	dic[a[i]] += 1

def dfs(u, rec):
	if dic[u * 2] >= 1:
		dic[u * 2] -= 1
		rec.append(u * 2)
		dfs(u * 2, rec)
		rec.pop(-1)
		dic[u * 2] += 1
	elif u % 3 == 0 and dic[u // 3] >= 1:
		dic[u // 3] -= 1
		rec.append(u // 3)
		dfs(u // 3, rec)
		rec.pop(-1)
		dic[u // 3] += 1
	elif len(rec) == N:
		print(' '.join(map(str, rec)))
		exit()
for i in range(N):
	dic[a[i]] -= 1
	dfs(a[i], [a[i]])
	dic[a[i]] += 1


def count(num):
	if num % 3 != 0:
		return 0
	return 1 + count(num // 3)
n = int(input())
a = [*map(int, input().split())]
b = [None] * n
c = [None] * n
for i in range(0, n):
	c[i] = i
for i in range(0, n):
	cnt = count(a[i])
	b[i] = cnt
c.sort(key=lambda id: (-b[id], a[id]))
for i in range(0, n):
	print(a[c[i]], end=' ')


n = int(input())
x = list(map(int, input().split()))
edge = [[] for i in range(n)]
for i in range(n):
	for j in range(n):
		if x[i] == x[j] * 3 or x[i] * 2 == x[j]:
			edge[i].append(j)
prev = []

def count1(q, i):
	p = i
	count2 = 0
	while q % p == 0:
		count2 += 1
		p *= i
	return count2
minimum = 10 ** 10
maximum = 0
res = 0
for i in range(n):
	if count1(x[i], 3) > maximum:
		res = i
		minimum = count1(x[i], 2)
		maximum = count1(x[i], 3)
	elif count1(x[i], 3) == maximum and count1(x[i], 2) < minimum:
		res = i
		minimum = count1(x[i], 2)
		maximum = count1(x[i], 3)
prev = [x[res]]
q = res
for i in range(n - 1):
	if len(edge[q]) == 2:
		if x[edge[q][0]] == prev[len(prev) - 1] * 2:
			prev.append(x[edge[q][0]])
			r = edge[q][1]
			edge[q] = [r]
			q = edge[q][0]
		else:
			prev.append(x[edge[q][1]])
			r = edge[q][0]
			edge[q] = [r]
			q = edge[q][1]
	elif len(edge[q]) == 1:
		prev.append(x[edge[q][0]])
		q = edge[q][0]
print(' '.join(map(str, prev)))


def buildIt(prevval, a, used, howmanyused):
	if howmanyused == len(a):
		return [prevval]
	for i in range(len(a)):
		if used[i] == False:
			if a[i] == prevval * 2:
				used[i] = True
				howmanyused += 1
				answer = buildIt(a[i], a, used, howmanyused)
				if answer != None:
					return [prevval] + answer
				else:
					used[i] = False
					howmanyused -= 1
			if prevval % 3 == 0 and a[i] == prevval // 3:
				used[i] = True
				howmanyused += 1
				answer = buildIt(a[i], a, used, howmanyused)
				if answer != None:
					return [prevval] + answer
				else:
					used[i] = False
					howmanyused -= 1
	return None
n = int(input())
a = [int(x) for x in input().split()]
used = [False for x in a]
howmany = 0
for i in range(len(a)):
	startval = a[i]
	used[i] = True
	howmanyused = 1
	tryit = buildIt(startval, a, used, howmanyused)
	if tryit != None:
		for x in tryit:
			print(x, end=' ')
		break
	else:
		used[i] = False


def fact(x):
	if x == 0:
		return 1
	else:
		return x * fact(x - 1)

def lower_bound(li, num):
	answer = -1
	start = 0
	end = len(li) - 1
	while start <= end:
		middle = (end + start) // 2
		if li[middle] >= num:
			answer = middle
			end = middle - 1
		else:
			start = middle + 1
	return answer

def upper_bound(li, num):
	answer = -1
	start = 0
	end = len(li) - 1
	while start <= end:
		middle = (end + start) // 2
		if li[middle] <= num:
			answer = middle
			start = middle + 1
		else:
			end = middle - 1
	return answer

def abs(x):
	return x if x >= 0 else -x

def binary_search(li, val, lb, ub):
	ans = 0
	while lb <= ub:
		mid = (lb + ub) // 2
		if li[mid] > val:
			ub = mid - 1
		elif val > li[mid]:
			lb = mid + 1
		else:
			ans = 1
			break
	return ans

def kadane(x):
	sum_so_far = 0
	current_sum = 0
	for i in x:
		current_sum += i
		if current_sum < 0:
			current_sum = 0
		else:
			sum_so_far = mpos(sum_so_far, current_sum)
	return sum_so_far

def pref(li):
	pref_sum = [0]
	for i in li:
		pref_sum.append(pref_sum[-1] + i)
	return pref_sum

def graph(n, m):
	adj = dict()
	for i in range(1, n + 1):
		adj.setdefault(i, 0)
	for i in range(m):
		(a, b) = map(int, input().split())
		adj[a] += 1
		adj[b] += 1
	return adj
import sys
import threading
from math import *
sys.setrecursionlimit(300000)
threading.stack_size(10 ** 8)

def pow_of_3(x):
	ans = 0
	while x % 3 == 0:
		ans += 1
		x //= 3
	return ans
for _ in range(1):
	n = int(input())
	a = list(map(int, input().split()))
	li = []
	for i in range(n):
		li.append((-pow_of_3(a[i]), a[i]))
	li.sort()
	for i in range(n):
		print(li[i][1], end=' ')
	print('')


import sys
import bisect
try:
	fin = open('in')
except:
	fin = sys.stdin
input = lambda : fin.readline().strip()

def f(x):
	c = 0
	while x % 3 == 0:
		x //= 3
		c += 1
	return c
n = int(input())
r = list(map(int, input().split()))
u = [(-f(i), i) for i in r]
u.sort()
print(*[k[1] for k in u])


def solve(n1):
	i = 0
	while n1 % 2 == 0:
		i += 1
		n1 //= 2
	return i
n = int(input())
arr = list(map(int, input().split()))
for i in range(n):
	arr[i] = [-solve(arr[i]), arr[i]]
arr = sorted(arr)[::-1]
for i in arr:
	print(i[1], end=' ')


import sys
sys.setrecursionlimit(1500)
n = int(input())
v = list(map(int, input().strip().split()))
visited = set()
counter = 0

def solve(curr, seq):
	seq.append(curr)
	visited.add(curr)
	if len(seq) == n:
		print(' '.join(map(str, seq)))
	elif len(seq) <= n:
		if curr * 2 in v and curr * 2 not in seq:
			solve(curr * 2, seq)
		if curr // 3 in v and curr % 3 == 0 and (curr // 3 not in seq):
			solve(curr // 3, seq)
while counter < n:
	curr = v[counter]
	counter += 1
	if curr in visited:
		continue
	solve(curr, [])


n = int(input())
a = list(map(int, input().split()))
b = []
for i in a:
	if i * 2 in a or (i % 3 == 0 and i // 3 in a):
		b.append(i)
		for j in b:
			if j * 2 in a:
				b.append(j * 2)
			elif j % 3 == 0 and j // 3 in a:
				b.append(j // 3)
		if len(b) == n:
			break
		else:
			b = []
for i in b:
	print(i)


class Graph:

	def __init__(self, n):
		self.n = n
		self.adj = [[] for i in range(n)]

	def add(self, v, u):
		self.adj[v].append(u)
n = int(input())
g = Graph(n)
a = list(map(int, input().split()))
for i in range(n):
	for j in range(n):
		if a[i] == 2 * a[j] or 3 * a[i] == a[j]:
			g.add(i, j)

def dfs(v):
	x = []
	used[v] = True
	for u in g.adj[v]:
		if used[u]:
			continue
		y = dfs(u)
		if len(y) > len(x):
			x = y
	x.append(v)
	return x
for i in range(n):
	used = [False for i in range(g.n)]
	ans = dfs(i)
	if len(ans) == n:
		break
for i in ans:
	print(a[i], end=' ')


def dfs(d, x):
	stack = [x]
	res = 1
	while stack:
		v = stack.pop()
		a = 0
		if v % 3 == 0:
			e = v // 3
			if d.get(e) != None:
				if d[e] > 0:
					d[e] -= 1
					stack.append(e)
					res += 1
					a = 1
		r = v * 2
		if d.get(r) != None:
			if d[r] > 0:
				d[r] -= 1
				stack.append(r)
				if a == 0:
					res += 1
	return res
n = int(input())
mas = list(map(int, input().split()))
di = {}
for (i, x) in enumerate(mas):
	if di.get(x) == None:
		di[x] = 0
	di[x] += 1
result = {}
for (i, x) in enumerate(mas):
	d = dict(di)
	res = dfs(d, x)
	result[res] = x
for i in range(n, 0, -1):
	print(result[i], end=' ')


def t(v: int):
	count = 0
	while v % 3 == 0:
		count += 1
		v //= 3
	return count
n = int(input())
a = list(map(int, input().split()))
ans = []
for i in a:
	ans.append((-t(i), i))
d = dict()
for i in ans:
	if i[0] in d:
		d[i[0]].append(i[1])
	else:
		d[i[0]] = [i[1]]
for i in sorted(list(d.keys())):
	print(*sorted(d[i]), end=' ')


n = int(input())
a = [int(x) for x in input().split()]
b = []
for i in range(n):
	if a[i] > 100000000:
		if a[i] * 3 not in a and a[i] // 2 not in a:
			b.append(a[i])
			a.pop(i)
			break
	elif a[i] * 3 not in a and a[i] / 2 not in a:
		b.append(a[i])
		a.pop(i)
		break
i = 0
while i < len(a):
	if a[i] == b[-1] * 2 or a[i] == b[-1] // 3:
		b.append(a[i])
		a.pop(i)
		i = 0
	else:
		i += 1
b = [str(x) for x in b]
print(' '.join(b))


from collections import defaultdict
g = defaultdict(list)
ans = []

def addEdge(g, u, v):
	g[u].append(v)

def dfs(v):
	visited[v] = 1
	for u in g[v]:
		if visited[u] == 0:
			ans.append(u)
			dfs(u)
n = int(input())
arr = [int(i) for i in input().split()]
b = arr[:]
visited = defaultdict(list)
for i in range(n):
	if arr[i] % 3 == 0 and arr[i] // 3 in arr:
		addEdge(g, arr[i], arr[i] // 3)
	if arr[i] * 2 in arr:
		addEdge(g, arr[i], arr[i] * 2)
	visited[arr[i]] = 0
for (key, val) in g.items():
	del b[b.index(val[0])]
start = b[0]
ans.append(start)
dfs(start)
print(*ans)


R = lambda : list(map(int, input().split(' ')))
n = int(input())
a = R()
answer = [a[0]]
while len(answer) < n:
	for i in range(n):
		if a[i] * 2 == answer[0] or answer[0] * 3 == a[i]:
			answer = [a[i]] + answer
		elif answer[-1] * 2 == a[i] or a[i] * 3 == answer[-1]:
			answer += [a[i]]
print(*answer)


from sys import stdin, stdout
from math import gcd, ceil, sqrt
ii1 = lambda : int(stdin.readline().strip())
is1 = lambda : stdin.readline().strip()
iia = lambda : list(map(int, stdin.readline().strip().split()))
isa = lambda : stdin.readline().strip().split()
mod = 1000000007
n = ii1()
arr = iia()

def logic(n):
	count = 0
	while n % 2 == 0:
		count += 1
		n //= 2
	return (-n, count)
arr.sort(key=logic)
print(*arr)


def deg(x):
	ret = 0
	while x % 3 == 0:
		ret += 1
		x //= 3
	return ret
n = int(input())
a = [int(i) for i in input().split()]
res = []
for i in a:
	res.append([-deg(i), i])
res.sort()
for i in res:
	print(i[1], end=' ')
print()


n = int(input())
a = list(map(int, input().split()))
count = []
for i in range(n):
	x = 1
	c = 0
	while a[i] % x == 0:
		x *= 3
		c += 1
	c -= 1
	count.append([-c, a[i]])
count.sort()
for i in range(n):
	print(count[i][1], end=' ')


from collections import defaultdict

def readline():
	return tuple(map(int, input().split()))

def main():
	n = int(input())
	seq = readline()
	pow2_clusters = defaultdict(list)
	for number in seq:
		pow2_clusters[number ^ number - 1].append(number)
	for (key, cluster) in sorted(pow2_clusters.items()):
		cluster.sort(reverse=True)
		print(' '.join(map(str, cluster)), end=' ')
main()


(n, s, v) = (int(input()), set(map(int, input().split())), [])
for x in s:
	if (x % 2 or x // 2 not in s) and x * 3 not in s:
		v.append(x)
for i in range(n - 1):
	if v[-1] % 3 == 0 and v[-1] // 3 in s:
		v.append(v[-1] // 3)
	elif v[-1] * 2 in s:
		v.append(v[-1] * 2)
print(' '.join(map(str, v)))


def f(x):
	i = 0
	z = x
	while z % 3 == 0:
		z //= 3
		i += 1
	return i
n = int(input())
a = list(map(int, input().split()))
x = [(-f(a[i]), a[i]) for i in range(n)]
x.sort()
print(' '.join([str(x[i][1]) for i in range(n)]))


def helper(curr, ans, l, visited, n):
	if l == n:
		for i in ans:
			print(i, end=' ')
		return True
	for i in arr:
		if i not in visited and (i * 3 == curr or i == curr * 2):
			visited.add(i)
			if helper(i, ans + [i], l + 1, visited, n):
				return True
			visited.remove(i)
	return False
n = int(input())
arr = [int(x) for x in input().split()]
for i in arr:
	v = set()
	v.add(i)
	if helper(i, [i], 1, v, n):
		break


from sys import stdin as si
from collections import Counter as C

class Solution:

	def bazinga(self, k, t):
		self.k = k
		self.stack = []
		for i in range(len(t)):
			self.stack = [t[i]]
			self.toing(t[:i] + t[i + 1:])

	def toing(self, d):
		x = self.stack[-1]
		if x * 2 in d:
			i = d.index(x * 2)
			self.stack.append(x * 2)
			self.toing(d[:i] + d[i + 1:])
			self.stack.pop(-1)
		if x % 3 == 0 and x // 3 in d:
			i = d.index(x // 3)
			self.stack.append(x // 3)
			self.toing(d[:i] + d[i + 1:])
			self.stack.pop(-1)
		if d == []:
			print(*self.stack)
			exit
n = int(si.readline().strip())
l = list(map(int, si.readline().strip().split()))
S = Solution()
S.bazinga(n, l)


from collections import defaultdict

class Graph:

	def __init__(self):
		self.graph = defaultdict(list)

	def addEdge(self, u, v):
		self.graph[u].append(v)

	def DFSUtil(self, v, visited):
		visited.add(v)
		ans.append(v)
		for neighbour in self.graph[v]:
			if neighbour not in visited:
				self.DFSUtil(neighbour, visited)

	def DFS(self, v):
		visited = set()
		self.DFSUtil(v, visited)
g = Graph()
n = int(input())
a = list(map(int, input().split()))
adj = [[] for _ in range(n + 1)]
src = [True] * n
ans = []
for i in range(n):
	for j in range(n):
		if i != j:
			if a[i] == 3 * a[j] or a[i] * 2 == a[j]:
				g.addEdge(i + 1, j + 1)
				src[j] = False
for i in range(n):
	if src[i] == True:
		source = i + 1
		break
g.DFS(source)
for x in ans:
	print(a[x - 1], end=' ')


n = int(input())
p = input().rstrip().split(' ')
q = list(p)
for i in range(0, len(p)):
	T = list(q)
	x = int(p[i])
	l = []
	U = 1
	K = 0
	l.append(x)
	while K < n - 1:
		K += 1
		if x % 3 == 0:
			x = x // 3
			if str(x) not in T:
				U = 0
				x = x * 3
			else:
				l.append(x)
		x = x * 2
		if str(x) not in T:
			x = x // 2
		else:
			l.append(x)
	if len(l) == n:
		break
print(*l)


n = int(input())
lst = list(map(int, input().split()))
ans = []
for i in range(n):
	for a in lst:
		if a * 2 in lst or (a % 3 == 0 and a // 3 in lst):
			continue
		else:
			ans.append(a)
			lst.remove(a)
print(' '.join([str(x) for x in ans[::-1]]))


from collections import Counter

def read_nums():
	return [int(x) for x in input().split()]

def solve(res, num, c, n):
	res.append(num)
	c[num] -= 1
	if n == 0:
		print(' '.join([str(x) for x in res]))
		exit()
	if num % 3 == 0 and num // 3 in c:
		solve(res, num // 3, c, n - 1)
		res.pop()
		c[num // 3] += 1
	if num * 2 in c:
		solve(res, num * 2, c, n - 1)
		res.pop()
		c[num * 2] += 1

def main():
	n = int(input())
	nums = read_nums()
	c = Counter(nums)
	res = []
	for num in nums:
		solve(res, num, c, n - 1)
		res.pop()
		c[num] += 1
main()


import sys
from collections import Counter
n = int(next(sys.stdin).rstrip())
xs = set(map(int, next(sys.stdin).rstrip().split()))
starters = set(xs)
for x in xs:
	if x % 2 == 0 and x // 2 in xs or x * 3 in xs:
		starters.remove(x)
assert len(starters) == 1
current = list(starters)[0]
sequence = [current]
while len(xs) != len(sequence):
	if current * 2 in xs:
		current *= 2
	else:
		current //= 3
		assert current in xs
	sequence.append(current)
print(' '.join(map(str, sequence)))


n = int(input())
arr2 = []
arr = [int(i) for i in input().split()]
for s in arr:
	k = s
	n3 = 0
	n2 = 0
	while k % 3 == 0:
		k = k % 3 + k // 3
		n3 += 1
	while k % 2 == 0:
		k = k // 2 + k % 2
		n2 += 1
	arr2.append((n3, n2, s))
arr2 = sorted(arr2, key=lambda x: -x[0])
b = arr2[0][0]
while b >= 0:
	a = sorted(list(filter(lambda x: x[0] == b, arr2)), key=lambda x: x[1])
	for j in a:
		print(j[2], end=' ')
	b -= 1


import sys
import bisect
import heapq
from math import *
from collections import Counter as counter
from itertools import combinations as comb
from itertools import permutations as permutate
from bisect import bisect_left as bl
from bisect import bisect_right as br
from bisect import bisect
mod = pow(10, 9) + 7

def inp():
	return sys.stdin.readline().strip()

def out(var):
	sys.stdout.write(str(var))

def lis():
	return list(map(int, inp().split()))

def stringlis():
	return list(map(str, inp().split()))

def sep():
	return map(int, inp().split())

def strsep():
	return map(str, inp().split())

def graph(vertex):
	return [[] for i in range(0, vertex + 1)]

def zerolist(n):
	return [0] * n

def nextline():
	out('\n')

def testcase(t):
	for p in range(t):
		solve()

def printlist(a):
	for p in range(0, len(a)):
		out(str(a[p]) + ' ')

def lcm(a, b):
	return a * b // gcd(a, b)

def solve():
	n = int(inp())
	a = lis()
	for i in range(0, n):
		if a[i] * 2 in a or (a[i] % 3 == 0 and a[i] // 3 in a):
			continue
		else:
			start = a[i]
			break
	new = [start]
	f = 0
	while f == 0:
		if start % 2 == 0 and start // 2 in a:
			new.append(start // 2)
			start = start // 2
		elif start * 3 in a:
			new.append(start * 3)
			start = start * 3
		else:
			f = 1
	print(*new[::-1])
testcase(1)


n = int(input())
arr = list(map(int, input().split()))
(MAX3, X) = (-1, -1)
Min2 = arr[0]
for i in range(n):
	x = arr[i]
	Min2 = min(Min2, x)
	while x % 2 == 0:
		x //= 2
	if x == MAX3:
		X = min(X, arr[i])
	if x > MAX3:
		MAX3 = x
		X = arr[i]
if MAX3 == -1:
	ANS = [Min2]
else:
	ANS = [X]
for i in range(n - 1):
	if ANS[-1] * 2 in arr:
		ANS += [ANS[-1] * 2]
	else:
		ANS += [ANS[-1] // 3]
print(*ANS)


n = int(input())
a = [int(i) for i in input().split(' ')]
path = []
for p in range(len(a)):
	path.append(-1)
b = []
for i in range(len(a)):
	b.append([-1, -1])
for x in range(len(a)):
	mul_two = a[x] * 2
	done = 0
	if a[x] % 3 == 0:
		done = 1
		div_thr = a[x] // 3
	for y in range(len(a)):
		if a[y] == mul_two:
			b[x][0] = y
			break
		elif done == 1:
			if a[y] == div_thr:
				b[x][1] = y
				break
for i in range(len(a)):
	cond = True
	k = i
	count = 0
	ans = 0
	path_var = 0
	for x in range(len(a)):
		path[x] = -1
	path[path_var] = a[i]
	path_var += 1
	while cond == True:
		if b[k][0] != -1:
			k = b[k][0]
			count += 1
			path[path_var] = a[k]
			path_var += 1
			if count == len(a) - 1:
				ans = 1
				break
		elif b[k][1] != -1:
			k = b[k][1]
			path[path_var] = a[k]
			path_var += 1
			count += 1
			if count == len(a) - 1:
				ans = 1
				break
		else:
			break
	if ans == 1:
		break
for i in range(len(path)):
	print(path[i], end=' ')


from collections import Counter
from copy import copy

def read_numbers():
	return (int(n) for n in input().strip().split(' '))

def solve(res, max_len, count):
	if len(res) == max_len:
		return res
	(first_path, second_path) = [None] * 2
	next1 = res[-1]
	if next1 % 3 == 0 and count[next1 // 3] > 0:
		count = copy(count)
		count[next1 // 3] -= 1
		first_path = solve([*res, next1 // 3], max_len, count)
	if count[next1 * 2] > 0:
		count = copy(count)
		count[next1 * 2] -= 1
		second_path = solve([*res, next1 * 2], max_len, count)
	if first_path:
		return first_path
	if second_path:
		return second_path
	return None

def main():
	input()
	numbers = list(read_numbers())
	count = Counter(numbers)
	for num in numbers:
		path = solve([num], len(numbers), count)
		if path:
			print(' '.join((str(i) for i in path)))
			return
main()


n = int(input())
a = list(map(int, input().split()))

def prime3_occurences(n):
	cont = 0
	while n % 3 == 0:
		n = n // 3
		cont += 1
	return cont
tups = []
for el in a:
	tups.append((prime3_occurences(el), el))
tups = sorted(tups, key=lambda x: (-x[0], x[1]))
a = [str(x[1]) for x in tups]
output = ' '.join(a)
print(output)


n = int(input())
L = list(map(int, input().split()))
L.sort()
min = L[0]
L1 = [L[0]]
while True:
	if min * 3 in L and min * 3 not in L1:
		min = min * 3
		L1 = [min] + L1
	elif min / 2 in L and min / 2 not in L1:
		min = min // 2
		L1 = [min] + L1
	else:
		break
min = L[0]
while True:
	if min / 3 in L and min / 3 not in L1:
		min = min // 3
		L1.append(min)
	elif min * 2 in L and min * 2 not in L1:
		min = min * 2
		L1.append(min)
	else:
		break
for i in L1:
	print(i, end=' ')


n = int(input())
b = list(map(int, input().split()))
a = dict()
for i in range(n):
	a[b[i]] = 0
start = -1
for i in b:
	if i * 3 not in a and (i % 2 != 0 or i // 2 not in a) and (start == -1):
		start = i
	if i * 2 in a:
		a[i] = i * 2
	elif i % 3 == 0 and i // 3 in a.keys():
		a[i] = i // 3
for i in range(n):
	print(start, end=' ')
	if start in a.keys():
		start = a[start]
	else:
		break


def main():
	from collections import deque
	N = int(input())
	A = [int(i) for i in input().split()]
	G = [[] for _ in range(N)]
	deg = [0] * N
	for i in range(N - 1):
		for j in range(i + 1, N):
			if A[i] * 2 == A[j] or (A[i] % 3 == 0 and A[i] // 3 == A[j]):
				G[i].append(j)
				deg[j] += 1
			if A[j] * 2 == A[i] or (A[j] % 3 == 0 and A[j] // 3 == A[i]):
				G[j].append(i)
				deg[i] += 1

	def topological_sort():
		que = deque()
		ans = [] * N
		for i in range(N):
			if deg[i] == 0:
				que.append(i)
				ans.append(i)
		while que:
			u = que.popleft()
			for v in G[u]:
				deg[v] -= 1
				if deg[v] == 0:
					que.append(v)
					ans.append(v)
		return ans
	order = topological_sort()
	print(*(A[i] for i in order))
main()


n = int(input())
a = list(map(int, input().split()))
aa = []
for i in range(n):
	tmp = a[i]
	p2 = 0
	while tmp % 2 == 0:
		tmp //= 2
		p2 += 1
	p3 = 0
	while tmp % 3 == 0:
		tmp //= 3
		p3 += 1
	aa.append((p2 - p3, i))
aa.sort()
ans = []
for (_, i) in aa:
	ans.append(a[i])
print(*ans)


def exp_3(a: int) -> int:
	ans = 0
	while a % 3 == 0:
		a //= 3
		ans += 1
	return ans

def exp_2(a: int) -> int:
	ans = 0
	while a % 2 == 0:
		a //= 2
		ans += 1
	return ans

def comp(a: int, b: int) -> bool:
	if exp_3(a) > exp_3(b):
		return -1
	elif exp_3(a) < exp_3(b):
		return 1
	elif exp_2(a) < exp_2(b):
		return -1
	else:
		return 1

def cmp_to_key(mycmp):

	class K:

		def __init__(self, obj, *args):
			self.obj = obj

		def __lt__(self, other):
			return mycmp(self.obj, other.obj) < 0

		def __gt__(self, other):
			return mycmp(self.obj, other.obj) > 0

		def __eq__(self, other):
			return mycmp(self.obj, other.obj) == 0

		def __le__(self, other):
			return mycmp(self.obj, other.obj) <= 0

		def __ge__(self, other):
			return mycmp(self.obj, other.obj) >= 0

		def __ne__(self, other):
			return mycmp(self.obj, other.obj) != 0
	return K

def solve(n: int, A: list):
	print(' '.join(list(map(str, sorted(A, key=cmp_to_key(comp))))))
n = int(input())
A = list(map(int, input().split()))
solve(n, A)


n = int(input())
a = list(map(int, input().split()))
g = [[0] * n for _ in range(n)]
for i in range(n):
	for j in range(n):
		if a[i] * 2 == a[j]:
			g[i][j] = 1
		if a[j] * 3 == a[i]:
			g[i][j] = 1

def dfs(u, b):
	for v in range(n):
		if g[u][v]:
			if dfs(v, b + [a[v]]):
				return True
	if len(b) == n:
		print(*b)
		return True
	return False
for u in range(n):
	if dfs(u, [a[u]]):
		break


n = int(input())
a = list(map(int, input().split()))
g = [-1] * n
for i in range(n):
	for j in range(n):
		if a[i] * 2 == a[j]:
			g[i] = j
		if a[j] * 3 == a[i]:
			g[i] = j
cur = g.index(-1)
result = [cur]
while cur in g:
	cur = g.index(cur)
	result.append(cur)
print(*[a[i] for i in result[::-1]])


n = int(input())
a = list(map(int, input().split()))
b = [[a[i], 0, 0] for i in range(n)]
for i in range(n):
	x = a[i]
	while x % 2 == 0:
		x = x // 2
		b[i][1] += 1
	while x % 3 == 0:
		x = x // 3
		b[i][2] += 1
b.sort(key=lambda x: (x[1], -x[2]))
c = [b[i][0] for i in range(n)]
print(*c)


import sys

def getfirstelement(a):
	for i in a:
		if i * 3 in a:
			continue
		if i % 2 == 0 and i // 2 in a:
			continue
		return i

def main():
	n = int(input())
	a = [int(i) for i in input().split()]
	x = getfirstelement(a)
	x = int(x)
	print(int(x))
	n -= 1
	while n:
		if x % 3 == 0 and int(x // 3) in a:
			x = int(x // 3)
		else:
			x = int(x * 2)
		print(int(x))
		n -= 1
main()


import math as mt
import sys, string, bisect
input = sys.stdin.readline
import random
from collections import deque, defaultdict
L = lambda : list(map(int, input().split()))
Ls = lambda : list(input().split())
M = lambda : map(int, input().split())
I = lambda : int(input())
n = I()
l = L()
m = []
for i in l:
	s = i
	c = 0
	while i % 3 == 0:
		c += 1
		i = i // 3
	m.append((s, c))
m.sort(key=lambda x: (-x[1], x[0]))
for i in m:
	print(i[0], end=' ')


import pprint as pp
n = int(input())
seq = list(map(int, input().split()))
graph = {i: None for i in seq}
for (i, x) in enumerate(seq):
	for j in seq[i:]:
		if x / 3 == j:
			graph[x] = j
		elif j / 3 == x:
			graph[j] = x
		if x * 2 == j:
			graph[x] = j
		elif j * 2 == x:
			graph[j] = x
x = None
for (i, j) in graph.items():
	if j == None:
		x = i
		break
path = [x]
graph.pop(x)
wat = True
while True:
	if x // 2 in graph:
		wat = False
		graph.pop(x // 2)
		path.append(x // 2)
		x = x // 2
	elif x * 3 in graph:
		wat = False
		graph.pop(x * 3)
		path.append(x * 3)
		x = x * 3
	else:
		break
if wat:
	path = seq[::-1]
for i in path[::-1][:-1]:
	print(i, end=' ')
print(path[0])


def divided_three_multiply_two(a):
	res = []
	for i in a:
		if i * 2 in a or (i % 3 == 0 and i // 3 in a):
			res.append(i)
			for j in res:
				if j // 3 in a and j % 3 == 0:
					res.append(j // 3)
				elif j * 2 in a:
					res.append(j * 2)
			if len(res) == len(a):
				break
			else:
				res = []
	return res
n = int(input())
p = list(map(int, input().split(' ')))
res = divided_three_multiply_two(p)
print(' '.join(map(str, res)))


def array_copy(src):
	trg = list()
	for each in src:
		trg.append(each)
	return trg

def recursion(src, progress, element, left):
	c = array_copy(src)
	c.remove(element)
	left -= 1
	if left == 0:
		out = ''
		for e in progress:
			out += '{} '.format(e)
		print(out)
		return False
	elif element % 3 == 0 and element // 3 in c:
		recursion(c, progress + [element // 3], element // 3, left)
	elif element * 2 in c:
		recursion(c, progress + [element * 2], element * 2, left)

def main():
	n = int(input())
	s = input().split()
	inp = list()
	for i in s:
		inp.append(int(i))
	for each in inp:
		recursion(inp, [each], each, n)
main()


def f(x):
	ans = 0
	while x % 3 == 0:
		x = x // 3
		ans += 1
	return ans
n = int(input())
l = [int(i) for i in input().split()]
for i in range(n):
	l[i] = [-f(l[i]), l[i]]
l.sort()
for i in range(len(l)):
	print(l[i][1], end=' ')
print()


def dfs(v):
	used[v] = 1
	now.append(v)
	for i in range(len(graph[v])):
		if not used[graph[v][i]]:
			dfs(graph[v][i])
n = int(input())
num = list(map(int, input().split()))
graph = [[] for i in range(n)]
for i in range(n):
	for j in range(n):
		if i != j:
			if num[j] * 3 == num[i]:
				graph[i].append(j)
			elif num[i] * 2 == num[j]:
				graph[i].append(j)
for i in range(n):
	now = []
	used = [0] * n
	dfs(i)
	if len(now) == n:
		ans = []
		for i in range(n):
			ans.append(num[now[i]])
		print(*ans)


from functools import reduce
import math
from decimal import *

def factors(n):
	return set(reduce(list.__add__, ([i, n // i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0)))

def sol():
	am = int(input())
	arr = list(map(int, input().split()))

	def f(n):
		c = 0
		while n % 2 == 0:
			c += 1
			n /= 2
		return (-n, c)
	arr.sort(key=f)
	print(*arr)
sol()


n = int(input())
a = list(map(int, input().split()))

def divisible(n):
	i = 0
	while n % 3 == 0:
		i += 1
		n = n // 3
	return (-i, n)
a.sort(key=divisible)
print(*a)


n = int(input())
s = [int(x) for x in input().split()]
d = {}
for i in range(n):
	q = s[i]
	t2 = 0
	while q % 2 == 0:
		q //= 2
		t2 += 1
	q = s[i]
	t3 = 0
	while q % 3 == 0:
		q //= 3
		t3 += 1
	d[t3, -t2] = s[i]
w = [i for i in d]
w.sort(reverse=1)
for i in range(n):
	print(d[w[i]], end=' ')


n = int(input())
a = list(map(int, input().split()))
(two, three) = ([], [])
for i in a:
	(tmp, three_tmp, two_tmp) = (i, 0, 0)
	while tmp % 3 == 0:
		tmp //= 3
		three_tmp += 1
	while tmp % 2 == 0:
		tmp //= 2
		two_tmp += 1
	two.append(two_tmp)
	three.append(three_tmp)
b = sorted(((two[i], -three[i], a[i]) for i in range(n)))
for (_, _, i) in b:
	print(i, end=' ')


def v3(x):
	ans = 0
	while x % 3 == 0:
		x //= 3
		ans += 1
	return ans

def v2(x):
	ans = 0
	while x % 2 == 0:
		x //= 2
	return ans
n = int(input())
arr = sorted(map(int, input().split()))
d = set()
mxpow3 = 0
pow3 = 0
mnpow2 = 1000
pow2 = 0
for num in arr:
	d.add(num)
	if v3(num) > mxpow3:
		mxpow3 = v3(num)
		pow3 = num
	if v2(num) < mnpow2:
		mnpow2 = v2(num)
		pow2 = num
cur = 0
tot = 0
if mxpow3 == 0:
	print(pow2, end=' ')
	cur = pow2
	tot += 1
else:
	print(pow3, end=' ')
	cur = pow3
	tot += 1
while tot < n:
	if 2 * cur in d:
		cur = 2 * cur
		print(cur, end=' ')
	else:
		cur //= 3
		print(cur, end=' ')
	tot += 1


def ff(n):
	c = 0
	while n % 3 == 0:
		n = n // 3
		c += 1
	return c
from math import *
n = int(input())
a = list(map(int, input().split()))
f = []
for i in range(len(a)):
	f.append([-ff(a[i]), a[i]])
f.sort()
for i in f:
	print(i[1], end=' ')


z = input
mod = 10 ** 9 + 7
from collections import *
from queue import *
from sys import *
from collections import *
from math import *
from heapq import *
from itertools import *
from bisect import *
from collections import Counter as cc
from math import factorial as f

def lcd(xnum1, xnum2):
	return xnum1 * xnum2 // gcd(xnum1, xnum2)

def prime(x):
	p = ceil(x ** 0.5) + 1
	for i in range(2, p):
		if x % i == 0:
			return 0
	return 1
num = int(z())
l = sorted(list(map(int, z().split())))
for j in l[::-1]:
	p = j
	nl = []
	for i in range(num):
		if p % 3 == 0 and p // 3 in l:
			nl.append(p)
			p = p // 3
		else:
			nl.append(p)
			p = p * 2
	if l == sorted(nl):
		print(*nl)
		exit(0)


def Alfa(a):
	m.append(a)
	if a % 3 == 0 and a // 3 in z:
		z.remove(a)
		Alfa(a // 3)
	elif a * 2 in z:
		z.remove(a)
		Alfa(a * 2)
	elif len(m) == n:
		for i in m:
			print(i, end=' ')
p = []
n = int(input())
k = sorted(map(int, input().split()))
k = k[::-1]
d = []
for i in k:
	m = []
	z = k.copy()
	Alfa(i)


n = int(input())
arr = []
for ai in list(map(int, input().split())):
	(num, cnt) = (ai, 0)
	while ai % 3 == 0:
		ai //= 3
		cnt += 1
	arr.append([-cnt, num])
arr.sort()
print(' '.join(list(map(lambda x: str(x[1]), arr))))


input()
d = set(list(map(int, input().strip().split())))
x = min(d)
d.remove(x)
sol = [x]
while d:
	if x * 2 in d:
		x = x * 2
		sol.append(x)
		d.remove(x)
	elif x % 3 == 0 and x // 3 in d:
		x = x // 3
		sol.append(x)
		d.remove(x)
	else:
		break
sol2 = []
x = sol[0]
while d:
	if x * 3 in d:
		x = x * 3
		sol2.append(x)
		d.remove(x)
	elif x % 2 == 0 and x // 2 in d:
		x = x // 2
		sol2.append(x)
		d.remove(x)
sol = list(reversed(sol2)) + sol
print(' '.join(map(str, sol)))


n = int(input())
a = list(map(int, input().split()))
ans = []
ans.append(a[0])
a.pop(0)
while len(a) != 0:
	for i in range(len(a)):
		if a[i] * 2 == ans[0] or ans[0] * 3 == a[i]:
			ans.insert(0, a[i])
			a.pop(i)
			break
		elif a[i] == ans[len(ans) - 1] * 2 or ans[len(ans) - 1] == a[i] * 3:
			ans.append(a[i])
			a.pop(i)
			break
		else:
			pass
for v in ans:
	print(v, end=' ')
print()


from collections import defaultdict
n = int(input())
a = list(map(int, input().split()))
Set = set(a)
graph = defaultdict(list)
for e in a:
	if e * 2 in Set:
		graph[e].append(e * 2)
	if e % 3 == 0 and e // 3 in Set:
		graph[e].append(e // 3)

def dfs(vertex):
	if len(vertex) == 0:
		return []
	return dfs(list(graph[vertex[0]])) + vertex
best = []
for each in a:
	ans = dfs([each])
	if len(ans) > len(best):
		best = ans
print(*best[::-1])


n = int(input())
a = input().split()
ans = []
for i in range(n):
	a[i] = int(a[i])
a.sort()
j = 0
while len(a) > 0:
	temp = []
	i = 0
	while i < len(a):
		if a[i] % 3 != 0:
			temp.append(a[i] * pow(3, j))
			a.remove(a[i])
		else:
			a[i] //= 3
			i += 1
	j += 1
	ans.append(temp)
k = len(ans)
for i in range(k):
	for j in range(len(ans[k - i - 1])):
		print(ans[k - i - 1][j], end=' ')


n = int(input())
l = list(map(int, input().split()))
po = []
for i in range(n):
	temp = l[i]
	c = 0
	while temp % 3 == 0:
		c -= -1
		temp //= 3
	po.append([c, l[i]])
po.sort(key=lambda k: (k[0], -k[1]), reverse=True)
for i in po:
	print(i[1], end=' ')


from collections import defaultdict

def dfs(num, cnt, path):
	global n, G
	if cnt == n:
		return path
	for node in G[num]:
		res = dfs(node, cnt + 1, path + [node])
		if res is not None:
			return res
n = int(input())
numberSet = set([int(x) for x in input().split()])
G = defaultdict(list)
for number in numberSet:
	if number << 1 in numberSet:
		G[number].append(number << 1)
	if number % 3 == 0 and number // 3 in numberSet:
		G[number].append(number // 3)
for number in numberSet:
	path = dfs(number, 1, [number])
	if path is not None:
		print(' '.join([str(node) for node in path]))
		break


n = int(input())
a = map(int, input().split())
b = []
for x in a:
	y = x
	cnt = 0
	while y % 3 == 0:
		y //= 3
		cnt += 1
	b.append([-cnt, x])
b = sorted(b)
for x in b:
	print(x[1], end=' ')


N = int(input())
l = []
w = []
used = 0
res = []
orig = []
l_t = list(map(int, input().split()))
for (a, b) in enumerate(l_t):
	l.append((b, a))
	orig.append((b, a))
while used < N:
	tmp = [i for i in l if i[0] % 2 != 0]
	w.append(tmp)
	used += len(tmp)
	for i in tmp:
		l.remove(i)
	for i in range(len(l)):
		l[i] = (l[i][0] // 2, l[i][1])
for i in range(len(w)):
	w[i].sort(key=lambda a: a[0], reverse=True)
for i in range(len(w)):
	for j in w[i]:
		res.append(orig[j[1]][0])
print(*res)


import collections

class Toposort(object):

	def __init__(self, g):
		self.g = g
		self.visited = [False] * len(g)
		self.stack = []
		for v in range(len(g)):
			if not self.visited[v]:
				self._sort(v)
		self.stack.reverse()

	def _sort(self, v):
		self.visited[v] = True
		for i in self.g[v]:
			if not self.visited[i]:
				self._sort(i)
		self.stack.append(v)

def main():
	n = int(input())
	numbs = list(map(int, input().strip().split()))
	d = collections.defaultdict(list)
	for (i, numb) in enumerate(numbs):
		d[numb].append(i)
	g = [set() for _ in numbs]
	for (i, numb) in enumerate(numbs):
		if numb % 3 == 0:
			for j in d[numb // 3]:
				if i != j:
					g[i].add(j)
		for j in d[numb * 2]:
			if i != j:
				g[i].add(j)
	t = Toposort(g)
	print(' '.join([str(numbs[i]) for i in t.stack]))
main()


def possible(arr, x):
	nums = {}
	for i in arr:
		if i not in nums.keys():
			nums[i] = 0
		nums[i] += 1
	ans = [x]
	while True:
		if x % 3 == 0 and x // 3 in nums.keys():
			x = x // 3
		elif 2 * x in nums.keys():
			x = 2 * x
		else:
			return False
		ans.append(x)
		nums[x] -= 1
		if nums[x] == 0:
			del nums[x]
		if len(ans) == len(arr):
			break
	for i in ans:
		print(i, end=' ')
	return True

def main():
	n = int(input())
	arr = list(map(int, input().split()))
	for i in arr:
		if possible(arr, i):
			return
main()


(n, l) = (int(input()), sorted(map(int, input().split()), reverse=True))
for i in l:
	(a, x) = ([i], l.copy())
	x.remove(i)
	while len(a) != n:
		p = a[-1] // 3 if a[-1] % 3 == 0 else -1
		(q, b) = (a[-1] * 2, True)
		for j in x:
			if j == p:
				a.append(p)
				x.remove(p)
				b = False
				break
			elif j == q:
				a.append(q)
				x.remove(q)
				b = False
				break
		if b:
			break
	if len(a) == n:
		exit(print(*a))


from sys import stdin, stdout

def main():
	n = int(stdin.readline())
	a = [int(i) for i in stdin.readline().split()]
	d = dict()
	for v in a:
		v3 = 0
		vc = v
		while vc % 3 == 0:
			vc = vc // 3
			v3 += 1
		temp = d.get(v3, [])
		temp.append(v)
		d[v3] = temp
	k = list(d.keys())
	k.sort()
	k.reverse()
	out = []
	for i in k:
		temp = d[i]
		temp.sort()
		out += temp
	stdout.write(' '.join([str(i) for i in out]) + '\n')
main()


n = int(input())
a = list(map(int, input().split()))
d = {}
for i in a:
	d[i] = 1
ans = {}
for i in a:
	if 2 * i in d:
		ans[i] = 2 * i
	if i % 2 == 0 and i // 2 in d:
		ans[i // 2] = i
	if 3 * i in d:
		ans[3 * i] = i
	if i % 3 == 0 and i // 3 in d:
		ans[i] = i // 3
for i in ans:
	flg = 0
	for j in ans:
		if ans[j] == i:
			flg = 1
	if flg == 0:
		st = i
		break
an = []
i = st
while i in ans:
	an.append(i)
	i = ans[i]
an.append(i)
print(*an)


from collections import deque

def read():
	return [int(v) for v in input().split()]

def div_by_3_mul_by_2(a):
	h = set(a)
	d = deque()
	d.append(a[0])
	while True:
		t = d[-1]
		if t * 2 in h:
			d.append(t * 2)
		elif t % 3 == 0 and t // 3 in h:
			d.append(t // 3)
		else:
			break
	while True:
		t = d[0]
		if t % 2 == 0 and t // 2 in h:
			d.appendleft(t // 2)
		elif t * 3 in h:
			d.appendleft(t * 3)
		else:
			break
	return list(d)

def main():
	_ = read()
	a = read()
	for v in div_by_3_mul_by_2(a):
		print(v, end=' ')
main()


from collections import *
import sys
input = lambda : sys.stdin.readline().strip()
orddict = OrderedDict
defdict = defaultdict
counter = Counter

def nextint():
	return int(input())

def snexts():
	return input().split(' ')

def snextint():
	return map(int, snexts())
mv = 50
n = nextint()
lis = map(int, input().split())
powers = [[] for _ in range(mv)]
for i in lis:
	amt = 0
	ti = i
	while ti % 3 == 0:
		amt += 1
		ti //= 3
	powers[amt].append(i)
final = []
for i in range(mv - 1, -1, -1):
	final.extend(sorted(powers[i]))
print(' '.join(map(str, final)))


def ord(n, k):
	res = 0
	while n % k == 0:
		n //= k
		res += 1
	return res
n = int(input())
a = list(map(int, input().split()))
a.sort(key=lambda x: (-ord(x, 3), ord(x, 2)))
print(*a)


def dfs(p, n):
	ans.append(a[p])
	v[p] = True
	if len(ans) == n:
		for i in ans:
			print(i, end=' ')
		exit()
	for j in range(0, n):
		if v[j] == False and (a[j] * 3 == ans[-1] or 2 * ans[-1] == a[j]):
			dfs(j, n)
		else:
			continue
	return
n = int(input())
a = list(map(int, input().split()))
for i in range(0, n):
	ans = list()
	v = [False] * n
	dfs(i, n)


def main():
	(n, l) = (int(input()), [])
	for a in map(int, input().split()):
		b = a
		two = three = 0
		while not a % 2:
			a //= 2
			two += 1
		while not a % 3:
			a //= 3
			three -= 1
		l.append((three, two, b))
	print(*[t[2] for t in sorted(l)])
main()


import math
from decimal import *
l1 = int(input())
l2 = input().split()
l2 = [int(i) for i in l2]
c = []
for i in range(l1):
	obj = {}
	obj['orig'] = l2[i]
	x = Decimal(l2[i])
	calc = Decimal(0)
	while x % 3 == 0:
		calc += 1
		x /= 3
	obj['calc'] = -calc
	c.append(obj)
c.sort(key=lambda x: (x['calc'], x['orig']))
for i in range(l1):
	print(str(c[i]['orig']) + ' ', end='')


from functools import reduce
from math import gcd
n = int(input())

def dlog(n, p):
	cnt = 0
	while n % p == 0:
		cnt += 1
		n //= p
	return cnt
l = [*map(int, input().split())]
g = reduce(gcd, l)
aux = sorted(((-dlog(l[i] // g, 3), dlog(l[i] // g, 2), i) for i in range(n)))
print(*[l[i] for (_, __, i) in aux])


from __future__ import division, print_function
import os, sys
from io import BytesIO, IOBase
if sys.version_info[0] < 3:
	from __builtin__ import xrange as range
	from future_builtins import ascii, filter, hex, map, oct, zip

def ii():
	return int(input())

def si():
	return input()

def mi():
	return map(int, input().strip().split(' '))

def msi():
	return map(str, input().strip().split(' '))

def li():
	return list(mi())

def dmain():
	sys.setrecursionlimit(1000000)
	threading.stack_size(1024000)
	thread = threading.Thread(target=main)
	thread.start()
import sys
input = sys.stdin.readline
scanner = lambda : int(input())
string = lambda : input().rstrip()
get_list = lambda : list(read())
read = lambda : map(int, input().split())
get_float = lambda : map(float, input().split())

def ceil(x):
	if x != int(x):
		x = int(x) + 1
	return x

def factorial(x, m):
	val = 1
	while x > 0:
		val = val * x % m
		x -= 1
	return val

def fact(x):
	val = 1
	while x > 0:
		val *= x
		x -= 1
	return val

def swaparr(arr, a, b):
	temp = arr[a]
	arr[a] = arr[b]
	arr[b] = temp

def gcd(a, b):
	if b == 0:
		return a
	return gcd(b, a % b)

def lcm(a, b):
	return a * b // math.gcd(a, b)

def is_integer(n):
	return math.ceil(n) == math.floor(n)

def nCr(n, k):
	if k > n:
		return 0
	if k > n - k:
		k = n - k
	res = 1
	for i in range(k):
		res = res * (n - i)
		res = res / (i + 1)
	return int(res)

def primefs(n):
	primes = {}
	while n % 2 == 0 and n > 0:
		primes[2] = primes.get(2, 0) + 1
		n = n // 2
	for i in range(3, int(n ** 0.5) + 2, 2):
		while n % i == 0 and n > 0:
			primes[i] = primes.get(i, 0) + 1
			n = n // i
	if n > 2:
		primes[n] = primes.get(n, 0) + 1
	return primes

def power(x, y, p):
	res = 1
	x = x % p
	if x == 0:
		return 0
	while y > 0:
		if y & 1 == 1:
			res = res * x % p
		y = y >> 1
		x = x * x % p
	return res

def swap(a, b):
	temp = a
	a = b
	b = temp
	return (a, b)

def find(x, link):
	p = x
	while p != link[p]:
		p = link[p]
	while x != p:
		nex = link[x]
		link[x] = p
		x = nex
	return p

def union(x, y, link, size):
	x = find(x, link)
	y = find(y, link)
	if size[x] < size[y]:
		(x, y) = swap(x, y)
	if x != y:
		size[x] += size[y]
		link[y] = x

def sieve(n):
	prime = [True for i in range(n + 1)]
	(prime[0], prime[1]) = (False, False)
	p = 2
	while p * p <= n:
		if prime[p] == True:
			for i in range(p * p, n + 1, p):
				prime[i] = False
		p += 1
	return prime

def phi(n):
	result = n
	p = 2
	while p * p <= n:
		if n % p == 0:
			while n % p == 0:
				n = n // p
			result = result * (1.0 - 1.0 / float(p))
		p = p + 1
	if n > 1:
		result = result * (1.0 - 1.0 / float(n))
	return int(result)

def is_prime(n):
	if n == 0:
		return False
	if n == 1:
		return True
	for i in range(2, int(n ** (1 / 2)) + 1):
		if not n % i:
			return False
	return True

def next_prime(n, primes):
	while primes[n] != True:
		n += 1
	return n
MAXN = int(100000.0 + 5)

def spf_sieve():
	spf[1] = 1
	for i in range(2, MAXN):
		spf[i] = i
	for i in range(4, MAXN, 2):
		spf[i] = 2
	for i in range(3, ceil(MAXN ** 0.5), 2):
		if spf[i] == i:
			for j in range(i * i, MAXN, i):
				if spf[j] == j:
					spf[j] = i
spf = [0 for i in range(MAXN)]

def factoriazation(x):
	res = []
	for i in range(2, int(x ** 0.5) + 1):
		while x % i == 0:
			res.append(i)
			x //= i
	if x != 1:
		res.append(x)
	return res

def factors(n):
	res = []
	for i in range(1, int(n ** 0.5) + 1):
		if n % i == 0:
			res.append(i)
			res.append(n // i)
	return list(set(res))

def int_array():
	return list(map(int, input().strip().split()))

def float_array():
	return list(map(float, input().strip().split()))

def str_array():
	return input().strip().split()

def binary_search(low, high, w, h, n):
	while low < high:
		mid = low + (high - low) // 2
		if check(mid, w, h, n):
			low = mid + 1
		else:
			high = mid
	return low

def check(beauty, s, n, count):
	pass

def sortSecond(val):
	return val[1]
MOD = int(1000000000.0) + 7
CMOD = 998244353
INF = float('inf')
NINF = -float('inf')
alphs = 'abcdefghijklmnopqrstuvwxyz'
from itertools import permutations
import math
import bisect as bis
import random
import sys
import collections as collect

def divisible(n):
	i = 0
	while n % 2 == 0:
		i += 1
		n //= 2
	return (-n, i)

def solve():
	n = scanner()
	a = get_list()
	a.sort(key=divisible)
	print(*a)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
if sys.version_info[0] < 3:
	(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
for i in range(1):
	solve()


def f(x):
	i = 0
	while x % 3 == 0:
		x //= 3
		i -= 1
	while x % 2 == 0:
		x //= 2
		i += 1
	return i
input()
a = list(map(int, input().split()))
a = sorted(a, key=f)
print(*a)


def main():
	n = int(input())
	a = [int(x) for x in input().split()]
	b = set(a)
	for e in a:
		ans = [e]
		b = set(a)
		b.remove(e)
		cur = e
		flag = True
		while flag and len(b):
			if cur % 3 == 0 and cur // 3 in b:
				cur = cur // 3
				ans.append(cur)
				b.remove(cur)
			elif cur * 2 in b:
				cur = cur * 2
				ans.append(cur)
				b.remove(cur)
			else:
				flag = False
		if flag:
			print(' '.join((str(x) for x in ans)))
			break
main()


import sys
import math
import collections
import operator as op
from collections import deque
from math import gcd, inf, sqrt, pi, cos, sin, ceil, log2, floor
from bisect import bisect_right, bisect_left
from functools import reduce
from sys import stdin, stdout, setrecursionlimit
setrecursionlimit(2 ** 20)

def ncr(n, r):
	r = min(r, n - r)
	numer = reduce(op.mul, range(n, n - r, -1), 1)
	denom = reduce(op.mul, range(1, r + 1), 1)
	return numer // denom

def prime_factors(n):
	i = 2
	factors = []
	while i * i <= n:
		if n % i:
			i += 1
		else:
			n //= i
			factors.append(i)
	if n > 1:
		factors.append(n)
	return list(factors)

def sumDigits(no):
	return 0 if no == 0 else int(no % 10) + sumDigits(int(no / 10))
MOD = 1000000007
PMOD = 998244353
N = 10 ** 9 + 7
LOGN = 30
T = 1
for _ in range(T):
	n = int(stdin.readline())
	a = list(map(int, stdin.readline().rstrip().split()))
	s = []
	for i in range(n):
		deg = 0
		val = a[i]
		while val % 3 == 0:
			val = val // 3
			deg += 1
		s.append([-deg, a[i]])
	s.sort()
	for i in range(n):
		print(s[i][1], end=' ')
	print()


from sys import stdin, stdout
cin = stdin.readline
cout = stdout.write

def test(k):
	try:
		val = d[k]
		return 1
	except KeyError as e:
		return 0
n = int(cin())
d = {i: 1 for i in list(map(int, cin().split()))}
l = [0] * n
for i in d:
	l[0] = i
	for j in range(n - 1):
		if l[j] % 3 == 0 and test(l[j] // 3):
			l[j + 1] = l[j] // 3
		elif test(l[j] * 2):
			l[j + 1] = l[j] * 2
		else:
			break
	else:
		for j in l:
			cout(str(j) + ' ')


n = int(input())
T = input().split(' ')
for i in range(n):
	T[i] = int(T[i])
for w in range(n):
	bol = True
	L = [T[w]]
	for j in range(n - 1):
		if 2 * L[j] in T and 2 * L[j] not in L:
			L.append(2 * L[j])
		elif L[j] % 3 == 0 and L[j] // 3 in T and (L[j] // 3 not in L):
			L.append(L[j] // 3)
		else:
			bol = False
			break
	if bol:
		for i in range(n - 1):
			print(L[i], end=' ')
		print(L[n - 1])
		break
	else:
		bol = True
		L = [T[w]]
		for j in range(n - 1):
			if 3 * L[j] in T and 3 * L[j] not in L:
				L.append(3 * L[j])
			elif L[j] % 3 == 0 and L[j] // 3 in T and (L[j] // 3 not in L):
				L.append(L[j] // 3)
			else:
				bol = False
				break
		if bol:
			for i in range(n - 1):
				print(L[n - 1 - i], end=' ')
			print(L[0])
			break


n = input()
c = {}
for x in [int(x) for x in input().split()]:
	(u, t) = (x, 0)
	while 0 == u % 3:
		u //= 3
		t += 1
	c[t] = c.get(t, []) + [x]
for x in sorted(c)[::-1]:
	for y in sorted(c[x]):
		print(y, end=' ')


def m3(n):
	cnt = 0
	while n % 3 == 0:
		cnt += 1
		n //= 3
	return cnt
n = int(input())
l = list(map(int, input().split()))
a = []
for i in range(n):
	x = m3(l[i])
	a.append((-x, l[i]))
a.sort()
for i in range(n):
	print(a[i][1], end=' ')


n = int(input())

def k(x):
	twos = 0
	while x % 2 == 0:
		x //= 2
		twos += 1
	threes = 0
	while x % 3 == 0:
		x //= 3
		threes += 1
	return (twos, -threes)
A = sorted(map(int, input().split()), key=k)
print(' '.join(map(str, A)))


from operator import itemgetter
n = int(input())
a = [int(s) for s in input().split()]
at = []
for i in range(n):
	ai = a[i]
	f2 = 0
	f3 = 0
	while ai % 2 == 0:
		f2 += 1
		ai >>= 1
	while ai % 3 == 0:
		f3 += 1
		ai //= 3
	at.append((a[i], f2, f3))
at_sorted = sorted(sorted(at, key=itemgetter(1)), key=itemgetter(2), reverse=True)
ans = ''
for ai in at_sorted:
	ans += str(ai[0]) + ' '
print(ans.strip())


def main():
	n = int(input())
	a = list(map(int, input().split(' ')))
	for item in a:
		current = item
		copy = list(a)
		sequence = [current]
		copy.remove(current)
		while copy:
			divided = current // 3
			multiplied = current * 2
			if divided in copy and current % 3 == 0:
				copy.remove(divided)
				sequence.append(divided)
				current = divided
			elif multiplied in copy:
				copy.remove(multiplied)
				sequence.append(multiplied)
				current = multiplied
			else:
				break
		if set(sequence) == set(a):
			return ' '.join(map(str, sequence))
print(main())


n = int(input())
a = list(map(int, input().split()))
memo = {}
for i in range(50):
	memo[i] = []
for i in range(n):
	tmp = a[i]
	cnt = 0
	while True:
		if tmp % 3 == 0:
			cnt += 1
			tmp //= 3
		else:
			break
	memo[cnt].append(a[i])
ans = []
for i in range(50)[::-1]:
	tmp = memo[i]
	tmp = sorted(tmp)
	for i in tmp:
		ans.append(i)
print(*ans)