50 likes | 234 Vues
Sorting. Sorting. A common activity for programmers to do is sort. You’ve been asked to do this for your last project. There are many ways to sort data We will look at sorting arrays You will have to generalize this to sorting an ArrayList. Two Basic Sorts. Bubble sort A horrible sort.
E N D
Sorting • A common activity for programmers to do is sort. • You’ve been asked to do this for your last project. • There are many ways to sort data • We will look at sorting arrays • You will have to generalize this to sorting an ArrayList
Two Basic Sorts • Bubble sort • A horrible sort. • Very slow and no redeeming qualities • But it is very easy to implement • Selection sort • Not much better than bubble sort • It is still slow but not as slow as bubble sort • It is also very easy to implement
Selection Sort for (passCount = 0; passCount<length-1;passCount++ ) { minIndx = passCount; for (srchIndx=passCount+1;srchIndx<length;srchIndx++) if ( data[srchIndx] < data[minIndx] ) minIndx = srchIndx; temp = data[minIndx]; data[minIndx] = data[passCount]; data[passCount] = temp; } }
Things to Note • The temp variable used in the swapping, must be of the same type as the array. • minIndex, passCount, srchIndex, length are all integers • Length is the length of the array • More specifically, it is the number of locations in the array that have been used.