Skip to content

Instantly share code, notes, and snippets.

@joxer
Last active March 8, 2018 20:19
Show Gist options
  • Save joxer/048df94a5e5c8643cfc178cbb4d42de8 to your computer and use it in GitHub Desktop.
Save joxer/048df94a5e5c8643cfc178cbb4d42de8 to your computer and use it in GitHub Desktop.
Dutch Flag Problem
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [],
"source": [
"flag = [0,1,2,0,1,1,2,0,2,1,0,0,1,1,2,2]"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [],
"source": [
"mid_value = 1\n",
"low = 0\n",
"mid = 0\n",
"high = len(flag)-1"
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2]\n"
]
}
],
"source": [
"while mid <= high:\n",
" if flag[mid] < mid_value:\n",
" tmp = flag[low]\n",
" flag[low] = flag[mid]\n",
" flag[mid] = tmp\n",
" low +=1\n",
" mid +=1\n",
" elif flag[mid] == mid_value:\n",
" mid +=1\n",
" elif flag[mid] > mid_value:\n",
" tmp = flag[high]\n",
" flag[high] = flag[mid] \n",
" flag[mid] = tmp\n",
" high -= 1\n",
" \n",
"print(flag)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3.6",
"language": "python",
"name": "python36"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.3"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment