Tuesday, April 3, 2007

Lecture 28

Sorting

  • A fundamental task of computer science
  • given an array , put the array in order
int a[]= {3,9,0,2,6}
sort(a);
a=0,2,3,6,9

Sorting Strategies

  1. Bubble Sort
    • take the unsorted array and start at the top
    • traverse the list until you find an element out of order
    • using pairwise exchanges move the out of order element toward the top of the list until it is in order
    • continue until the end of the list
    • once an out of order element is found we float it to the correct position
Example

  1. 39026
  2. 30926
  3. 03926
  4. 03296
  5. 02396
  6. 02369
Divide and Conquer Sorting

  • nobody uses bubblesort for anything serious
  • better methods:
    • mergesort
    • quicksort
  • if the list is of size > 1 then
    1. divide the list into two sublists
    2. sort each sublist
    3. join the two sublists
  • else
    1. do nothing
  • these are recursive sorting algorithms
  • all the actio nhappens in the splitting and joining
public static void Sort(int[]a, int begin, int end)
//sorts the subvector of 'a' from beginning to end inclusive
{
if (end - begin > 0)
{
int S = split(a,beginning,end)
sort(a,begin,S);
sort(a,S+1,end;
join(a,begin,S,end)
}

  • MergeSort
    • split is simple
    • join is complicated
  • QuickSort
    • split is complicated
    • join is simple

MergeSort
  • Split
    • splits the list down the middle
    • returns (begin + end )/ 2
  • Join
    • two sorted Lists
    • merge them in order

Example

038249
038 249
0<2
2<3
3<4
4<8
8<9
023489


42091

420:91
  • 42:0
    • 4:2
    • 4 //done
    • 2 //done
      • join(2,4)
        • 24
          • join(24,0)
            • 024
  • 9:1
    • 9 //done
    • 1 //done
      • join(9,1)
        • 19
  • join(024,91)
    • 01249

No comments: