虽能给我发一个有关快速排序算法的程序

jsa 2003-08-23 09:14:24
简单的实现就行。我实在搞不明白快速排序了!!!
C++或Pascal均可。
jamessmy@163.net
...全文
92 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
zzwu 2003-08-23
  • 打赏
  • 举报
回复

以下是Quicksort Algorithm的源代码例子:


#include <stdio.h>

int A[] = { 99, 43, 22, 17, 57, 32, 43, 19, 26, 48, 87, 12, 75, 0 };
const int numEntries = sizeof(A)/sizeof(int);

void qksort(int ilo, int ihi) {
int pivot; // pivot value for partitioning array
int ulo, uhi; // indices at ends of unpartitioned region
int ieq; // least index of array entry with value equal to pivot
int tempEntry; // temporary entry used for swapping

if (ilo >= ihi) {
return;
}
// Select a pivot value.
pivot = A[(ilo + ihi)/2];
// Initialize ends of unpartitioned region and least index of entry
// with value equal to pivot.
ieq = ulo = ilo;
uhi = ihi;
// While the unpartitioned region is not empty, try to reduce its size.
while (ulo <= uhi) {
if (A[uhi] > pivot) {
// Here, we can reduce the size of the unpartitioned region and
// try again.
uhi--;
} else {
// Here, A[uhi] <= pivot, so swap entries at indices ulo and
// uhi.
tempEntry = A[ulo];
A[ulo] = A[uhi];
A[uhi] = tempEntry;
// After the swap, A[ulo] <= pivot.
if (A[ulo] < pivot) {
// Swap entries at indices ieq and ulo.
tempEntry = A[ieq];
A[ieq] = A[ulo];
A[ulo] = tempEntry;
// After the swap, A[ieq] < pivot, so we need to change
// ieq.
ieq++;
// We also need to change ulo, but we also need to do
// that when A[ulo] = pivot, so we do it after this if
// statement.
}
// Once again, we can reduce the size of the unpartitioned
// region and try again.
ulo++;
}
}
// Now, all entries from index ilo to ieq - 1 are less than the pivot
// and all entries from index uhi to ihi + 1 are greater than the
// pivot. So we have two regions of the array that can be sorted
// recursively to put all of the entries in order.
qksort(ilo, ieq - 1);
qksort(uhi + 1, ihi);
}

void qksort(void) {
qksort(0, numEntries - 1);
}

void printArray(void) {
for (int i = 0; i < numEntries; i++) {
printf(" %d\n", A[i]);
}
printf("\n");
}

int main(void) {
printf("Before sorting, the entries of A are:\n");
printArray();
qksort();
printf("After sorting, the entries of A are:\n");
printArray();
}


Compilation Command
g++ -Wall -o quicksort quicksort.C

Execution Command
quicksort

Program Output
Before sorting, the entries of A are:
99
43
22
17
57
32
43
19
26
48
87
12
75
0

After sorting, the entries of A are:
0
12
17
19
22
26
32
43
43
48
57
75
87
99





jsa 2003-08-23
  • 打赏
  • 举报
回复
Thanks Very Much!!!!!!!!

33,009

社区成员

发帖
与我相关
我的任务
社区描述
数据结构与算法相关内容讨论专区
社区管理员
  • 数据结构与算法社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧