80 likes | 214 Views
Internal Sorting. File Sorting Part 2. Bubble Sort of an array. Inefficient --- O ( N 2 ) easy to code , hence unlikely to contain errors Algorithm for outerloop = 1 to N for innerloop = 0 to N-2 if ( item[ innerloop ] > item[innerloop+1] )
E N D
Internal Sorting File Sorting Part 2
Bubble Sort of an array Inefficient --- O ( N2 ) easy to code, hence unlikely to contain errors 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 • Easy to code, less swapping than bubble, but still O ( N2 ) • Splits the array into 2 lists: • one sorted (which slowly grows) • one unsorted (which slowly shrinks) • Algorithm • find the smallest item in unsorted list • swap smallest with start of unsorted list • sorted_size ++; and unsorted_size --;
Quick Sort of an array • Very Fast --- O ( N log2 N ) • A pain to program • Algorithm • recursively partition the array into sub-lists • sort infileoutfile …… it's magic !!! animations and comparisons at http://www.sorting-algorithms.com/
Sorting a Linked List • Linked Lists are necessary when we don't know the size of the list • Sorting Operations for both arrays and linked lists • comparisons • arrays - need multiple indexes • LL - need multiple pointers • swaps • 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 40 20 60 10 30 70 Alternative to building Singly Linked List Inserting new node is much easier Traversal to find insertion is log2N So, inserting N items takes N * log2 N compares