Algorithms and OOD (CSC 207 2013F) : EBoards

CSC207.01 2013F, Class 37: Pause for Breath: Sorting


Overview

Preliminaries

Admin

Questions on HW9

Some comments on git and github

Formatting issues

Why might the following upset me?

int indexOfSmallest(T[] vals, Comparator<T> order, int lb, int ub) {
    Integer index;
        Integer minIndex = lb;
    for ( index = lb + 1; index < ub; index++){
                if ( order.compare(vals[minIndex], vals[index]) > 0){
                        minIndex = index;
                }
        }
    return minIndex;
} // indexOfSmallest(T[], Comparator<T>, int, int)

Code you should never write

What should happen to a 161 student who writes the following at the end of the semester?

char *str = (char *) malloc(12 * sizeof(char));
str = "Hello world";

Important lesson: In C, when you assign to a pointer, you change what it points to.

Related lesson: In Java, when you assign to an object, you're just assigning a pointer (although we call it a reference).

String a = "Hello"; String b = "Goodbye"; String c = a; a = b;

What's the relation to that and the following Java?

T[] values = (T[]) new Object[computedSize];
values = merge(vals1, lb1, ub1, vals2, lb2, ub2, order);

indexOfSmallest

What's wrong with the following code?

int indexOfSmallest(T[] vals, Comparator<T> order, int lb, int ub) {
    int i = 0;      // Fix i = lb
    while(i<vals.length){
        if (order.compare(vals[i], vals[lb]) < 0) { // Fix i = ub
            lb = i;
        }
        i++;
    }
    return lb;
} // indexOfSmallest(T[], Comparator<T>, int, int)

What happens if we use this for selection sort?

5, 1, 6, 2, 8, 3
*

1, 5, 6, 2, 8, 3
!  *

5, 1, 6, 2, 8, 3
!  !  *

Partition for Quicksort

The code we develop can be found in examples/sorting-pause

Iterative merge sort

The code we develop can be found in examples/sorting-pause

Copyright (c) 2013 Samuel A. Rebelsky.

Creative Commons License

This work is licensed under a Creative Commons Attribution 3.0 Unported License. To view a copy of this license, visit http://creativecommons.org/licenses/by/3.0/ or send a letter to Creative Commons, 543 Howard Street, 5th Floor, San Francisco, California, 94105, USA.