Tải bản đầy đủ - 0 (trang)
4 (Optional) A GUI for Insertion Sorting

4 (Optional) A GUI for Insertion Sorting

Tải bản đầy đủ - 0trang

simplercases.Fornow,letususeintegerdatabetween0and99,which

willeliminatetheproblemoffiguringouttheverticalscale;werepresenta

valueof59withabarofheight59pixels.Tofindthewidthofeachbar,

wedividethewidthoftheformbythesizeofthedata,dividingtheform

intoequalpartsforeachbar.

TousetheFillRectanglemethodtodrawourbars,weneedthe

upper-leftcornerforeachbaranditsheightandwidth.Figure9.10shows

thechartwithafewbars.





Figure9.10:Partofabarchart





Figure9.11:ThechartofExample9.8

Becausethecoordinateoriginisintheupper-leftcornerofthecanvas,

theupper-leftcornerofthebarrepresentingthearrayelementitem[i]

is(i*width,100-item[i])wherewidthisthecommonwidthof

eachbar,givenbyCHART_WIDTH/count,andcountisthenumberof

elementsenteredthusfar.



IntheOnPaintmethod,wedrawabarchartshowingthevaluesentered

sofar.Figure9.11showsthechartaftertheuserentersthevalues53,

22,and75.Example9.8givesthecodeforthisexploration.

Example9.8:InsertA.cs



/*Usesatextboxtoenterdataandaform

*todisplaythechart.Thisisanexploratory

*programtodevelopaGUIforinsertionsort.

*/



usingSystem;

usingSystem.Drawing;

usingSystem.Windows.Forms;

publicclassInsertA:Form{

publicconstintITEM_SIZE=10;

publicconstintCHART_HEIGHT=100;

publicconstintCHART_WIDTH=400;



privateTextBoxnumber=newTextBox();

privateButtonsubmit=newButton();



int[]item=newint[ITEM_SIZE];//Datatosort//Note

intcount=0;//Sizeofdata



publicInsertA(){



//Setcaptions

Text="Chart";

submit.Text="Submit";



//Setsize

Size=newSize(400,200);



//Setlocations

submit.Location=newPoint(20,130);

number.Location=newPoint(30+submit.Width,130);





//Configurecontrols

AcceptButton=submit;



//Addcontrolstoform

Controls.Add(number);

Controls.Add(submit);



//Registereventhandler

submit.Click+=newEventHandler(Submit_Click);

}



/*Handlesbuttonclick.Entersnewdatainarray.

*Redrawsthechart.

*/

protectedvoidSubmit_Click(Objectsender,EventArgse){

item[count++]=int.Parse(number.Text);//Note

number.Text="";

number.Focus();//Note

Invalidate();//Note

}



//Drawsthechart

protectedoverridevoidOnPaint(PaintEventArgse){

Graphicsg=e.Graphics;

if(count>0){//Note

intwidth=CHART_WIDTH/count;//Note

for(inti=0;i
g.FillRectangle(Brushes.Red,i*width,

CHART_HEIGHT-item[i],width,item[i]);//Note

}

}

publicstaticvoidMain(){

Application.Run(newInsertA());

}

}



Note



1. int[]item=newint[ITEM_SIZE];

Weuseanarrayofsize10forsimplicity,butlaterwill

allowdifferentsizesofdata.

2. item[count++]=int.Parse(number.Text);

WhentheuserclickstheSubmitbutton,wegetthe

valuefromthetextfield,convertittoaninteger,save

itinthenextpositioninthearray,andincrementthe

countoftheitemsenteredsofar.

3. number.Focus();

Afterhandlingtheevent,wereturnthefocustothe

textboxsotheuserwillnothavetoclickthemouse

beforeenteringanothervalue.

4. Invalidate();

Becausetheuserjustenteredanothervalue,we

generateaPainteventtoredrawthechartincluding

thisnewvalue.

5. if(count>0){

Whentheapplicationstarts,.NETwillcallthis

OnPaintmethodtodrawtheformoncebeforethe

userhasachancetoenteranyvalues.Whilethe

countisstillzero,wedonotwanttodrawachart.

6. intwidth=CHART_WIDTH/count;

Togetthewidthofeachbar,wedividethewidthof

thechart,CHART_WIDTH,bythenumberofdata

items,size.

7. g.FillRectangle(Brushes.Red,i*width,

CHART_HEIGHT-item[i],

width,item[i]);



Figure9.10showsafewbarsofthechart.Wecan

seefromthisfigurehowtogetthecoordinatesofthe

upper-leftcornerofeachbar.Thedatavalueitself

givestheheightofthebar,becausewedonotneed

toscalethedata.



DesigningaSolution:Sorting

Wecanimprovethechartlater,butatleastExample9.8showsthatwe

areontherighttrack.Forournextstep,letustrytosortthedata.Each

timetheuserentersanothervalue,wecaninsertitintheorderofits

predecessors.TodothiswecancopythecodefromExample7.8intoan

InsertNextmethodtowhichwepassthearrayofdataandthenumber

ofelementssofar.Thearrayholds10elements,butiftheuserentered

thethirdelement,forexample,theInsertNextmethodshouldinsert

thatvalueinthecorrectpositionwithrespecttoitstwopredecessors,

ignoringthearrayvaluesbeyondthethird.

Figure9.12showsthechartjustaftertheuserentersthevalues53,22,

and75;aswecansee,thevaluesaresorted.Example9.9showsthe

additionstoExample9.8neededtodothesorting.





Figure9.12:ThesortedchartofExample9.9

Example9.9:InsertB.cs

/*AddanInsertNextmethodtoinserteachvalue

*inorderassoonastheuserentersit.

*/

publicclassInsertB:Form{

//TherestisthesameasExample9.8





protectedvoidSubmit_Click(Objectsender,EventArgse){

item[count]=int.Parse(number.Text);

InsertNext(item,count++);//Note

number.Text="";

number.Focus();

Invalidate();

}

publicvoidInsertNext(int[]data,intsize){//Note

intcurrent=data[size];

intj=0;

while(current>data[j])

j++;

for(intk=size;k>j;k--)

data[k]=data[k-1];

data[j]=current;

}

}



Note



1. InsertNext(item,count++);

Weinsertthenextvalueinthecorrectpositionas

soonastheuserentersitinthetextboxandclicks

theSubmitbuttontogeneratetheClickevent.

2. publicvoidInsertNext(int[]data,int

size){

Wecopiedthecodeforinsertingthenextelement

fromExample7.8.



Wearemakingprogress,butthechartdoesnotlookverynicewithevery

barthesamecolor.Wecangreatlyimprovetheappearanceofthechart

bydrawingadjacentbarsindifferentcolors.Todothisweaddthissimple

statement

if(i%2==0)

b=Brushes.Blue;



else

b=Brushes.Red;

totheOnPaintmethodtosetthecolortoblueiftheindexisevenandto

redotherwise.Wewillseethisimprovementinournextexample.



DesigningaSolution:TheUserInterface

Nowthatwearecomfortablewiththesortinganddrawing,wecanthink

abouttheuserinterface.Wewillkeepthetextboxfortheusertoenter

datavaluesandaddanothertextboxfortheusertospecifythesizeof

thearray.

AsinExample7.8,itisnicetobeabletoselectrandominputgenerated

bythecomputerormanualinputfromtheuserinthetextfield.Weadd

tworadiobuttonstomaketheseselections.Weaddanotherbuttonto

usewhensortingtherandomnumbers.

LetusseehowtheGUIlooksbeforewetrytomakeitwork.InExample

9.10weaddthenewcomponents,butdonotrespondtoanyevents

otherthanthetextentryofExample9.9.Figure9.13showsournewGUI.





Figure9.13:TheGUIofExample9.10

Example9.10:InsertC.cs

/*AddscontrolstoExample9.9

*/



usingSystem;



usingSystem.Drawing;

usingSystem.Windows.Forms;

publicclassInsertC:Form{

publicconstintITEM_SIZE=10;

publicconstintCHART_HEIGHT=100;

publicconstintCHART_WIDTH=400;



//Createcontrols

privateTextBoxnumber=newTextBox();

privateButtonsubmit=newButton();

privateRadioButtonrandom=newRadioButton();

privateRadioButtonmanual=newRadioButton();

privateLabelsize=newLabel();

privateTextBoxgetSize=newTextBox();

privateButtonsort=newButton();



int[]item=newint[ITEM_SIZE];//Datatosort

intcount=0;//Sizeofdata



publicInsertC(){



//Setcaptions

Text="Chart";

submit.Text="Submit";

random.Text="Random";

manual.Text="Manual";

size.Text="Size";

getSize.Text="10";

sort.Text="Sort";



//Setsize

Size=newSize(400,200);



//Setlocations

intw=10;

random.Location=newPoint(w,105);

manual.Location=newPoint(w,130);



size.Location=newPoint(w+=random.Width,105);

getSize.Location=newPoint(w,130);

sort.Location=newPoint(w+=getSize.Width,105);

number.Location=newPoint(w+=sort.Width,130);

submit.Location=newPoint(w+10,105);



//Configurecontrols

AcceptButton=submit;



//Addcontrolstoform

Controls.Add(number);

Controls.Add(submit);

Controls.Add(random);

Controls.Add(manual);

Controls.Add(size);

Controls.Add(getSize);

Controls.Add(sort);

//Registereventhandler

submit.Click+=newEventHandler(Submit_Click);

}

//TherestisthesameasExample9.9

}



CompletingtheC#Code:MakingtheUserInterfaceWork

OurattemptataGUI,showninFigure9.13,looksreasonableenoughto

attempttocontinuetheimplementation.Beforegettingintothedetailsof

theimplementationweneedtolookatafewtechniqueswewillneed.

Wecandisableacontrolcusingthestatement

c.Enabled=false;

andenableitwith

c.Enabled=true;

Weshoulddisablecomponentswhentheyshouldnotbeused.For



example,whentheuserselectsrandomdata,weshoulddisablethetext

fieldthatallowstheusertoinputdatamanually.Untilwearereadyto

handlerepeatedsortingwithdifferentdata,weshoulddisablemostofthe

componentsafterwecompletethefirstsort.

Inadditiontogettingdatafromatextboxorreadingthelabelofabutton,

wecanalsosetthesestringstodesiredvalues.Wecanclearthetextbox

aftereachdataentry,sotheuserwillnothavetodeletetheprevious

valuetoenteranewone.AftertheuserpressestheSortbuttontostart

thesorting,wecanchangethatbutton'slabeltoNextsotheusercan

commandthatweinsertthenextvalue.

ReturningtoourGUI,wewillstartwithboththeSortbuttonandthedata

entrytextboxdisabled.Iftheuserselectsrandominputweenablethe

Sortbutton,butiftheuserselectsmanualinputweenablethedataentry

field.Nomatterwhattypeofinputtheuserselects,wedisablebothradio

buttonsafterthefirstselectionbecausewewillnotyethandlerepeated

sortingorchangesintheinputmethod.

Inputtingmanually,whentheusersubmitsthefirstnumbertheevent

handlerwillallocateanarrayandgetthesizeforitfromtheothertext

fieldinwhichtheuserspecifiedthearraysize.Weinitializethisfieldwith

adefaultsizeof10.Weacceptdataentryonlyuntiltheuserhasentered

thespecifiednumberofelements.Afterprocessingthelatestentryweset

thetextboxtexttotheemptystringtomakeiteasierfortheusertoenter

thenextelement.

WeusetheSortbuttonforrandominput.Onthefirstpress,whenthe

buttonhasitsoriginallabel,Sort,theeventhandlergetsthedesiredsize

ofthedata,createsthearray,andfillsitwithrandomnumbersfrom0to

99.ItgeneratesaPainteventtodisplaythedata,andchangesthe

button'slabeltoNextsotheusercanstartinsertingtheitemsoneby

one.

EachtimetheuserpressestheNextbutton,theeventhandlerinsertsthe

nextelementinorderwithrespecttoitspredecessorsandgeneratesa

Painteventtodisplaythedata.Thusweseethesortingprocessstepby-step.Theeventhandlerdisablesthebuttonwhenalltheelements



havebeeninsertedandthedataiscompletelysorted.





Figure9.14:TheGUIofExample9.11

Figure9.14showsthesortingpartiallycompleted.Example9.11shows

thechangesfromExample9.10neededtomaketheapplicationrespond

totheeventsgeneratedbytheuser.

Example9.11:InsertD.cs

/*Providesauserinterfaceforinsertionsorting.

*Theusercanchooserandomdataorinputvalues

*manually.Theuserspecifiesthesizeofthedata.

*Astheuserinsertseachitem,thechartisredisplayed.

*/



usingSystem;

usingSystem.Drawing;

usingSystem.Windows.Forms;

publicclassInsertD:Form{

publicconstintITEM_SIZE=10;

publicconstintCHART_HEIGHT=100;

publicconstintCHART_WIDTH=400;



//Createcontrols

privateTextBoxnumber=newTextBox();

privateButtonsubmit=newButton();

privateRadioButtonrandom=newRadioButton();

privateRadioButtonmanual=newRadioButton();

privateLabelsize=newLabel();

privateTextBoxgetSize=newTextBox();

privateButtonsort=newButton();



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

4 (Optional) A GUI for Insertion Sorting

Tải bản đầy đủ ngay(0 tr)

×