Searching and Sorting: CSE 130: Introduction To Programming in C Spring 2005
Searching and Sorting: CSE 130: Introduction To Programming in C Spring 2005
Pseudocode
Binary Search If (range contains only one element):
else
• Ex. Find 29
int mid = (first + last)/2;
if (value == A[mid])
5 6
Sorting Techniques Bubble Sort
• Many sorting techniques exist: quicksort, • Method: compare pairs of adjacent items,
radix sort, mergesort, bubblesort, insertion and swap them if they are “out of order”
sort, shell sort, selection sort, etc.
• At the end of each pass, the largest
• These techniques differ in efficiency remaining element is in its proper place
• Different sorting techniques take different • Elements “bubble” to their proper places
amounts of time to sort the same data
• This is a very easy algorithm to implement
• The rate of time increase also differs • It’s also very inefficient
7 8
9 10
11 12
Pseudocode Selection Sort Example
Start: [29, 10, 14, 37, 13]
After 1st pass: [29, 10, 14, 13, 37]
1. Repeat N-1 times:
After 2nd pass: [13, 10, 14, 29, 37]
1. Find the largest (unsorted) element
After 3rd pass: [13, 10, 14, 29, 37]
2. Swap A[last] with A[largest]
After 4th pass: [10, 13, 14, 29, 37]
End: [10, 13, 14, 29, 37]
13 14
15 16
• Begin by dividing the array into two regions: 1. nextItem = first unsorted element
sorted and unsorted
2. Shift sorted elements > nextItem over
• Initially, the sorted region is empty one position (A[x] = A[x-1])
• At each step, move first unsorted item into 3. Insert nextItem into correct position
its proper position in the sorted region
17 18
Insertion Sort Example Insertion Sort Code
• Start: [29 ][ 10, 14, 37, 13] int unsorted;
for (unsorted = 1; unsorted < N; unsorted++)
int loc;
• Move 37: [10, 14, 29, 37 ][ 13] for (loc = unsorted; (loc > 0) && (a[loc-1] > nextItem); loc--)
• Move 13: [10, 13, 14, 29, 37 ][ ] a[loc] = a[loc-1]; /* shift a[loc-1] to the right */
19 20