我是算法的新手,我很困惑我的代码中的错误在哪里作为一个赋值。我正在尝试在Python 3中实现一个快速排序算法,它在数组中处理相同的值。
这是一个快速排序功能(代表阵列):
def randomized_quick_sort(a, l, r):
if l >= r:
return
k = random.randint(l, r)
a[l], a[k] = a[k], a[l]
m1, m2 = partition3(a, l, r)
randomized_quick_sort(a, l, m1 - 1);
randomized_quick_sort(a, m2 + 1, r);
这是我的分区功能:
def partition3(a, l, r):
x, j, t = a[l], l, r
for i in range(l + 1, r + 1):
if a[i] < x:
j +=1
a[i], a[j] = a[j], a[i]
elif a[i] > x:
a[i], a[t] = a[t], a[i]
t -=1
else:
j +=1
a[l], a[j] = a[j], a[l]
return j, t
答案 0 :(得分:8)
你应该纠正你的分区功能:
这是一个有效的例子:
var webpack = require('webpack');
var commonsPlugin =
new webpack.optimize.CommonsChunkPlugin('common.js');
module.exports = {
entry: {
main: './src/scripts/app/index.js',
vendor: [
"./src/scripts/lib/jquery.min.js",
"./src/scripts/lib/jquery.qtip/jquery.qtip.min.js",
"./src/scripts/lib/jquery.qtip/imagesloaded.pkg.min.js"
]
},
output: {
path: __dirname + '/build',
publicPath: '/',
filename: '[name]-[hash].js'
},
node: {
filename: true,
process: true,
global: true
},
resolve: {
extensions: [
'', // Any
'.js', '.json', // Scripts & Scripts Data
'.vue', // Vue
'css', 'styl', // Styles
'png', 'jpg', 'gif', 'svg' // Images
]
},
module: {
loaders: [{
test: /\.vue$/,
loader: 'vue'
}, {
test: /\.js$/,
loader: 'babel'
}, {
test: /\.css$/,
loader: ['style', 'css']
}, {
test: /\.styl$/,
loader: ['style', 'css', 'stylus']
},{
test: /\.(png|jpg|gif|svg)$/,
loader: 'url',
query: {
// limit for base64 inlining in bytes
// Min 8KB
limit: 8 * 1024,
// custom naming format if file is larger than
// the threshold
name: '[name].[ext]?[hash]'
}
}]
},
plugins: [
commonsPlugin
]
};
答案 1 :(得分:7)
这是python中一个简单的快速实现。虽然它仍然是nlogn,但可以进行一系列性能优化。例如,可以在单次传递中进行分区为更小,相等,更大,而不是数组的3次传递。
def qsort(arr):
if len(arr) <= 1: return arr
pivot = arr[0]
less = [x for x in arr if x < pivot]
equal = [x for x in arr if x == pivot]
greater = [x for x in arr if x > pivot]
return qsort(less) + equal + qsort(greater)
要使该分区在数组的一次传递中发生,请创建一个如下的辅助函数:
def partition(arr, pivot):
less, equal, greater = [], [], []
for val in arr:
if val < pivot: less.append(val)
if val == pivot: equal.append(val)
if val > pivot: greater.append(val)
return less, equal, greater
def qsort(arr):
if len(arr) <= 1: return arr
pivot = arr[0]
less, equal, greater = partition(arr, pivot)
return qsort(less) + equal + qsort(greater)
答案 2 :(得分:0)
for loop
的另一个实现def partition3(a, l, r):
x = a[l]
m1 = l
m2 = l
i = m1
for i in range(l + 1, r + 1):
if a[i] < x:
a[i], a[m1] = a[m1], a[i]
a[i], a[m2+1] = a[m2+1], a[i]
m1 += 1
m2 += 1
elif a[i] == x:
a[i], a[m2+1] = a[m2+1], a[i]
m2 += 1
return m1, m2