def qsort(L):
if len(L) <= 1 : return L
return qsort([lt for lt in L[1:] if lt < L[0]]) + L[0:1] + qsort([ge for ge in L[1:] if ge>= L[0]])
|
很经典的快排实现。虽然看起来很短,解释器做了很多工作。但是这样看起来还是很优雅的。比起几十行的c/c++,漂亮很多~ 呵呵 顺便附上qsort的c实现,就不自己编码了,从网上找的,好久不写了,就不折磨自己了。。。
#include <stdlib.h>
#include <stdio.h>
#define NUM_ITEMS 100
void quickSort(int numbers[], int array_size);
void q_sort(int numbers[], int left, int right);
int numbers[NUM_ITEMS];
int main()
{
int i;
//seed random number generator
srand(getpid());
//fill array with random integers
for (i = 0; i < NUM_ITEMS; i++)
numbers[i] = rand();
//perform quick sort on array
quickSort(numbers, NUM_ITEMS);
printf("Done with sort.\n");
for (i = 0; i < NUM_ITEMS; i++)
printf("%i\n", numbers[i]);
}
void quickSort(int numbers[], int array_size)
{
q_sort(numbers, 0, array_size - 1);
}
void q_sort(int numbers[], int left, int right)
{
int pivot, l_hold, r_hold;
l_hold = left;
r_hold = right;
pivot = numbers[left];
while (left < right)
{
while ((numbers[right] >= pivot) && (left < right))
right--;
if (left != right)
{
numbers[left] = numbers[right];
left++;
}
while ((numbers[left] <= pivot) && (left < right))
left++;
if (left != right)
{
numbers[right] = numbers[left];
right--;
}
}
numbers[left] = pivot;
pivot = left;
left = l_hold;
right = r_hold;
if (left < pivot)
q_sort(numbers, left, pivot-1);
if (right > pivot)
q_sort(numbers, pivot+1, right);
}
|
阅读(926) | 评论(0) | 转发(0) |