您的位置:首页 > 其它

快速排序 普通和随机版本

2011-06-11 20:29 381 查看
#include <stdio.h>
#include <stdlib.h>
template <class Type>
void quick_sort(Type a[], int left, int right) {
if (left < right) {
int p = partion(a, left, right);
quick_sort(a, left, p - 1);
quick_sort(a, p + 1, right);
}
}
template <class Type>
int partion(Type a[], int left, int right) {
int i = left;
int j = right + 1;
Type divide = a[left];
while (true) {
while (a[++i] < divide && i < right);
while (a[--j] > divide);
if (i >= j) {
break;
}
swap(&a[i], &a[j]);
}
a[left] = a[j];
a[j] = divide;
return j;
}
template <class Type>
void swap(Type* a, Type* b) {
Type tmp = *a;
*a = *b;
*b = tmp;
}
int main(int argc, char** argv) {
int* a = (int*) malloc(100 * sizeof(int));
int i = 0;
while (scanf("%d", &a[i++]) != EOF && a[i - 1] != 0 && i < 100) {
quick_sort(a, 0, i - 1);
}
int n = 0;
for (n = 0; n < i; n++) {
printf("%d/t", a
);
}
}


#include <stdio.h>
#include <stdlib.h>
template <class Type>
void quick_sort(Type a[], int left, int right) {
if (left < right) {
int p = partion(a, left, right);
quick_sort(a, left, p - 1);
quick_sort(a, p + 1, right);
}
}

template <class Type>
int partion(Type a[], int left, int right) {
int i = left;
int j = right + 1;
Type divide = a[left];
while (true) {
while (a[++i] < divide && i < right);
while (a[--j] > divide);
if (i >= j) {
break;
}
swap(&a[i], &a[j]);
}
a[left] = a[j];
a[j] = divide;
return j;
}
template <class Type>
void swap(Type* a, Type* b) {
Type tmp = *a;
*a = *b;
*b = tmp;
}
int main(int argc, char** argv) {
int* a = (int*) malloc(100 * sizeof(int));
int i = 0;
while (scanf("%d", &a[i++]) != EOF && a[i - 1] != 0 && i < 100) {
quick_sort(a, 0, i - 1);
}
int n = 0;
for (n = 0; n < i; n++) {
printf("%d/t", a
);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: