Understanding BubbleSort CS-502 (EMC) Fall Understanding BubbleSort CS-502, Operating Systems Fall 2009 (EMC) (Slides include materials from Modern Operating Systems, 3 rd ed., by Andrew Tanenbaum and from Operating System Concepts, 7 th ed., by Silbershatz, Galvin, & Gagne)
Understanding BubbleSort CS-502 (EMC) Fall BubbleSort Code void BubbleSort (int A[], const int arraySize) { int i, j; for(i = 0; i abs(A[j+1])) swap(A+j, A+j+1); }//void BubbleSort(…) void swap (int *a, int *b) { int temp = *a; *a = *b; *b = temp; }//void swap(…) Note use of pointer arguments!
Understanding BubbleSort CS-502 (EMC) Fall Swap is easy void swap (int *a, int *b) { int temp = *a; *a = *b; *b = temp; }//void swap(…) Put the value pointed to by a in the location pointed to by b Put the value pointed to by b in the location pointed to by a Notice how swap reaches back to the caller’s data and changes it
Understanding BubbleSort CS-502 (EMC) Fall Bubble Sort Algorithm void BubbleSort (int A[], const int arraySize) { int i, j; for(i = 0; i abs(A[j+1])) swap(A+j, A+j+1); }//void BubbleSort(…) Fundamental principle –Let the “lighter” elements bubble to the top and the “heavier” elements sink to the bottom
Understanding BubbleSort CS-502 (EMC) Fall BubbleSort Code void BubbleSort (int A[], const int arraySize) { int i, j; for(i = 0; i abs(A[j+1])) swap(A+j, A+j+1); }//void BubbleSort(…) Loop invariant (loop i ) –The largest i elements are located at the bottom of the array in order.
Understanding BubbleSort CS-502 (EMC) Fall BubbleSort Code (continued) void BubbleSort (int A[], const int arraySize) { int i, j; for(i = 0; i abs(A[j+1])) swap(A+j, A+j+1); }//void BubbleSort(…) Loop invariant (loop j ) –Absolute value of A[j+1] ≥ any of the elements A[0] … A[j].
Understanding BubbleSort CS-502 (EMC) Fall BubbleSort Code void BubbleSort (int A[], const int arraySize) { int i, j; for(i = 0; i abs(A[j+1])) swap(A+j, A+j+1); }//void BubbleSort(…) Loop invariant (loop i ) The largest i elements are located at the bottom of the array in order. Loop invariant (loop j ) Absolute value of A[j+1] ≥ any of the elements A[0] … A[j]. Does invariant of loop j preserve the invariant of loop i ? Why?
Understanding BubbleSort CS-502 (EMC) Fall Answer Loop invariant i is true for i == 0 By inspection Suppose loop invariant i is true for some value i > 0 Is it true for i + 1? From this, can we conclude that it is true for the entire array?
Understanding BubbleSort CS-502 (EMC) Fall Questions?