Bubble Sort Notes David Beard CS181
Bubble Sort for Strings Double pass algorithm to sort a single dimensional array. Inner loop “bubbles” largest element to top/end of the array Outer loop runs inner loop enough times to “bubble” each element to its correct location Subsequent slides contain variation of bubble sort for integer array using a switch void function.
Invoking BubbleSort Routine Int aSize = 5; int a[cSize]; a[0] = 5; a[0] = 0; a[0] = 4; a[0] = 1; a[0] = 2; bubbleSort(a[], aSize); for (int I = 0; I <aSize; i++) cout << a[i]; cout << endl;
Bubble Sort for Integers void bubbleSort(int a[], int aSize) { int temp, bubblePass; for (int i = 0; i a[bubblePass+1]) { temp = a[bubblePass]; //does switch a[bubblePass] = a[bubblePass+1]; a[bubblePass+1] = temp; } }
Bubble Sort Algorithm with Integers Initial ordering: 2, 4, 6, 4, 8, 7, 9, 3 After first bubblePass: 2, 4, 4, 6, 7, 8, 3, 9 After second bubblepass: 2, 4, 4, 6, 7, 3, 8, 9 After third bubblepass: 2, 4, 4, 6, 3, 7, 8, 9 After fourth bubblepass: 2, 4, 4, 3, 6, 7, 8, 9 After fifth bubblepass: 2, 4, 3, 4, 6, 7, 8, 9 After sixth bubblepass: 2, 3, 4, 6, 7, 8, 9