sorting list is rearranged into sorted order how is the sorted order determined? – the itemtype is...

Post on 13-Jan-2016

218 Views

Category:

Documents

1 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Sorting

• List is rearranged into sorted order• How is the sorted order determined?– The ItemType is responsible for determining the

key to be used in comparison of instances of the item.

– The ItemType relational operator< determines the sorted order of the list.

• To be really efficient, we also need a fast sort algorithm.

Common Sort Algorithms Bubble Sort Heap Sort Selection Sort Merge Sort Insertion Sort Quick Sort

• There are many known sorting algorithms. Bubble sort is the slowest, running in n2 time. Quick sort is the fastest, running in n lg n time.

• As with searching, the faster the sorting algorithm, the more complex it tends to be.

Selection Sort• Selection sort algorithm: sorts a list by selecting

the smallest element in the list and then moving this element to the top of the list

• The first time we locate the smallest item in the entire list

• The second time we locate the smallest item in the rest of the list starting, etc.

Selection SortThe approach of Selection Sort:– select one value and put it in its final place in the sort list– repeat for all other values

In more detail:– find the smallest value in the list– switch it with the value in the first position– find the next smallest value in the list– switch it with the value in the second position– repeat until all values are placed

Selection SortAn example: sort the list 61, 39, 32, 21, 2, 37

pass 1: 61 39 32 21 2 37

pass 2: 2 39 32 21 61 37

pass 3: 2 21 32 39 61 37

pass 4: 2 21 32 39 61 37

pass 5: 2 21 32 37 61 39

result: 2 21 32 37 39 61

Selection Sort Routinevoid ListType::SelSort(){ ItemType item; int passCount; int searchIndx; int minIndx;

for (passCount = 0; passCount < length-1; passCount++) {

minIndx = passCount;

for (searchIndx = passCount+1; searchIndx<length; searchIndx++)

if (data[searchIndx] < data[minIndx])

minIndx = searchIndx;

item = data[minIndx];

data[minIndx] = data[passCount];

data[passCount] = item; }}

top related