[英]Cannot find issues with this Quicksort code
我正在用C ++編寫快速排序代碼。 當我為小型數組運行代碼時,代碼工作得很好,但是當元素數量很大(例如450)時,我遇到了問題。
我的代碼如下:(使用Visual Studio):
// algo_QuickSort.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include<stdio.h>
#include<iostream>
#include<conio.h>
#include<limits.h>
#include<time.h>
using namespace std;
int Partition(int master[6],int beg,int end)
{
cout<<"entered partition..";
int pivot=master[beg];
int i=beg+1,j=end;
do
{
for(;master[i]<pivot;)
{
i++;
}
for(;master[j]>pivot;)
{
j--;
}
if(i<j)
{
int temp=master[i];
master[i]=master[j];
master[j]=temp;
}
cout<<"i: "<<i<<endl;
cout<<"j: "<<j<<endl;
_getch();
}while(i<j);
_getch();
cout<<"exited while..";
if(i>=j)
{
int temp2=master[j];
master[j]=pivot;
master[beg]=temp2;
cout<<"before return..";
return j;
}
}
void QuickSort(int master[10001],int beg,int end)
{
cout<<"entered quicksort..";
if(beg<end)
{
int flag=Partition(master,beg,end);
QuickSort(master,beg,flag);
QuickSort(master,flag+1,end);
}
}
int _tmain(int argc, _TCHAR* argv[])
{
int A[10001];
clock_t start,end;
/*int A[6]={7,5,8,3,2};
A[5]=numeric_limits<int>::max();
QuickSort(A,0,5);
for(int i=0;i<5;i++)
cout<<A[i]<<" ";*/
for(int i=450;i<=10001;i+=450)
{
//cout<<"entered loop..";
for(int j=0;j<i;j++)
{
A[j]=rand()%i;
}
A[i]=numeric_limits<int>::max();
cout<<"here..";
start=clock();
QuickSort(A,0,i);
//cout<<"out of qs..";
end=clock();
cout<<i<<","<<(double)(end-start)/CLK_TCK<<endl;
}
return 0;
}
在這里您可以看到,在主功能中被注釋掉的部分是測試用例,對於該用例,代碼運行得非常好,並按升序打印數字。 但是當我運行大量代碼時, 它陷入了一種循環,所以我編寫了各種cout
和_getch()
來跟蹤值,這就是問題所在,
i的值為26,j的值為137。現在我的問題是,由於i<j
,為什么i的值不遞增和j遞減? do-while
循環正在工作,但是為什么值沒有更改。 有任何想法嗎?
Partition
這段代碼是有缺陷的。
if(i<j)
{
int temp=master[i];
master[i]=master[j];
master[j]=temp;
}
如果pivot == master[i] == master[j]
則該程序將永遠運行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.