Sorting & Searching Review
Selection Sort 1. Find the smallest element 2. Move to the front of the array (swap with front) 3. Repeat Steps 1&2, but ignoring the front
Selection Sort Animations sort/ sort/ ecturenotes/malamb/SortingDemos/Selecti onSortDemo.html ecturenotes/malamb/SortingDemos/Selecti onSortDemo.html cs162/javaProgs/sort/SelectSort.html cs162/javaProgs/sort/SelectSort.html
Selection Sort Example Code int currentMinIndex = 0; for (int front = 0; front < intArray.length; front++) { currentMinIndex = front; for (int i = front; i < intArray.length; i++) { if (intArray[i] < intArray[currentMinIndex]) { currentMinIndex = i; } int tmp = intArray[front]; intArray[front] = intArray[currentMinIndex]; intArray[currentMinIndex] = tmp; }
Bubble Sort 1. Start at the bottom / end of the array 2. Compare the two elements and swap them if the smaller number is on the bottom 3. Move up one 4. Repeat steps 1 through 3 until smallest number has "floated" to the top 5. Start at the bottom again and repeat the above steps for the next smallest number. This time, the front / top of the list can be ignored because the smallest number is guaranteed to be there.
Bubble Sort Animations rt/ rt/ cs162/javaProgs/sort/BubbleSort.html cs162/javaProgs/sort/BubbleSort.html
Bubble Sort Example Code int front = 0; int pos = 0; for (front = 0; front < intArray.length; front++) { for (pos = intArray.length-1; pos > front; pos--) { if (intArray[pos] < intArray[pos-1]) { int tmp = intArray[pos]; intArray[pos] = intArray[pos-1]; intArray[pos-1] = tmp; }
Linear Search 1. Start from the beginning of the list 2. Check if current element matches key 3. Move to next element 4. Repeat steps 2-3 until key is found or end of list is reached
Linear Search Example Code int key = 0;//key may be any value for(int i = 0; i < intArray.length; i++) { if (key == intArray[i]) return i; } return -1;
Binary Search 1. Assume sorted list 2. Go to the middle point 3. If the middle element matches the key, then the search is over 4. If key is less than middle element, go to the left (down), else go to the right (up) 5. Repeat steps 2-4 until key is found or when the left and right bounds pass each other
Binary Search Example Code int key = 0;//key may be any value int first = 0; int last = intArray.length-1;; int mid = 0; boolean found = false; while( (!found) && (first <= last) ) { mid = (first + last) / 2; if(key == intArray[mid]) found = true; if(key < intArray[mid]) last = mid - 1; if(key > intArray[mid]) first = mid + 1; }