Week 11: Sort

  • Introducing: runtime analysis, big-O notation.

  • Sorting: Selection sort, Bubble sort

1. Resources:

2. Selection Sort

// function: selectionSort
// input: L (int[]), the list to sort
// output: none
void selectionSort(int[] L) {
  for (int i= 0; i < L.length; i++) {
    int minIdx = i;
    for (int j = i+1; j < L.length; j++) {
      if (L[j] < L[minIdx]) {
        minIdx = j;
      }
    }
    swap(minIdx, i, L);
    printValues(L);
  }
}

// function: printValues
// input: L (int[]), the list to sort
// output: none
void printValues(int[] L) {
  for (int i = 0; i < L.length; i++) {
    int value = L[i];
    print(value + " ");
  }
  println();
}

// function: swap
// input: firstIdx (int)
// input: secondIdx (int)
// input: L (int[])
// output: none
void swap(int firstIdx, int secondIdx, int[] L) {
  int tmp = L[firstIdx];
  L[firstIdx] = L[secondIdx];
  L[secondIdx] = tmp;
}

void setup() {

   int[] testValues = {10, 4, 3, 0, 11, 8};
   printValues(testValues);
   selectionSort(testValues);

   // test code
   //swap(0, 1, testValues);
   //printValues(testValues);
}