1 / 6

Sorting

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.

amanda
Télécharger la présentation

Sorting

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 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.

  2. 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.

  3. 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.

  4. Selection Sort The 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

  5. Selection Sort pass 1: 61 39 32 21 2 37 An example: sort the list 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

  6. Selection Sort Routine void 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; } }

More Related