Internal Sorting File Sorting Part 2 Bubble Sort

Internal Sorting File Sorting Part 2

Bubble Sort of an array Inefficient --- O ( N 2 ) n easy to code, code hence unlikely to contain errors n n Algorithm for outerloop = 1 to N for innerloop = 0 to N-2 if ( item[innerloop] > item[innerloop+1] ) swap item[i] and item[i+1]

Selection Sort of an array n Easy to code, less swapping than bubble, but still O ( N 2 ) n Splits the array into 2 lists: ¨ one n sorted (which slowly grows) unsorted (which slowly shrinks) Algorithm 1. 2. 3. find the smallest item in unsorted list swap smallest with start of unsorted list sorted_size ++; and unsorted_size --;

Quick Sort of an array n Very Fast --- O ( N log 2 N ) n A pain to program n Algorithm ¨ recursively partition the array into sub-lists ¨ sort ? ? %$@*#!!!! …… it's magic !!! animations and comparisons at http: //www. sorting-algorithms. com/

Sorting a Linked List n Linked Lists are necessary when we don't know the size of the list n Sorting Operations for both arrays and linked lists ¨ comparisons n n ¨ arrays - need multiple indexes LL - need multiple pointers swaps n with big records, LL is easier: ¨ just move a few pointers

Insertion Sort of Linked List Oversimplified Algorithm: While not eof newptr = new record with data from file temp = head while (temp != NULL) if (newptr->key < temp->key) insert newptr before temp else temp = temp->next

Ordered Binary Tree n Alternative to building Singly Linked List n Inserting new node is much easier n Traversal to find insertion point goes from N/2 down to log 2 N 40 n So, inserting N items takes * log 2 N compares 20 10 N 60 30 70

Heap Sort n Heaps are later this semester.
- Slides: 8