黄土高原地区:关于快速排序法的一个问题。

来源:百度文库 编辑:杭州交通信息网 时间:2024/05/03 11:36:34
#include <stdio.h>

void SortIntegerArray(int array[],int n);
static int Partition(int array[],int n);

int main(void)
{
int i;
int a[] = {56,25,37,58,95,19,73,30};
printf("array before sorted:");
for(i=0;i<8;i++){
printf("%d\t",a[i]);
}
SortIntegerArray(a,8);
printf("\narray after sorted:");
for(i=0;i<8;i++){
printf("%d\t",a[i]);
}
printf("\n");

}

void SortIntegerArray(int array[],int n)
{
int boundary;
if(n<2) return;
boundary = Partition(array,n);
SortIntegerArray(array,boundary);
SortIntegerArray(array+boundary+1,n-boundary-1);
}

static int Partition(int array[],int n)
{
int lh,rh,pivot,temp;

pivot = array[0];
lh = 1;
rh = n-1;
while(1){
while(lh < rh&&array[rh] >= pivot) rh--;
while(lh < rh&&array[lh] <= pivot) lh++;
if(lh == rh) break;
temp = array[lh];
array[lh] = array[rh];
array[rh] = temp;
}
if(array[lh] >= pivot) return (0);
array[0] = array[lh];
array[lh] = pivot;
return(lh);
}

上面是代码,下面有个问题:
如果改变程序,以便在lh和rh所指位置元素进行交换之前,检查确保lh和rh所指位置元素值不同,很有可能比原算法运行的更慢,为什么会这样?