Sorting and Searching  1
21  Sorting and Searching
Being able to make sense of vast piles of data is incredibly important in the modern
world.
Searching
is the process of retrieving data and
sorting
is the process of organizing
it.
Efficient algorithms for both have vast commercial value.
Sorted Arrays
We say that an array A is sorted in
ascending
order if
A(1)
≤
A(2)
≤
A(3)
≤
...
≤
A(n)
while an array sorted in
descending
order will satisfy
A(1)
≥
A(2)
≥
A(3)
≥
...
≥
A(n)
Given an array with elements in any order, sorting is the process of moving the elements
within the array to produce a sorted array at the end. Sorting requires that the elements
have an order. That is, the < operator must be defined.
Bubble Sort
The
bubble sort
is a simple sorting algorithm that is easy to understand. (It is also
incredibly inefficient.
It has been said “the best thing about a bubble sort is its name”.
Anyway
…).
The bubble sort makes a
pointer
, which, in this case, is an index. It moves through the
data array element by element. (The “data array” is a vector which lists the data to be
sorted.)
This pointer "catches" the largest element it has seen so far and drags it along.
Thus the largest element "bubbles" through the other elements and eventually ends up at
the right end of the array – in the position
A(n).
Then the pointer starts at the left again
and bubbles through until it places the second largest element in the array at the right
hand side,
A(n1)
.
Continuing this way, the pointer sorts the array. Here is the code to do a bubble sort:
This preview has intentionally blurred sections. Sign up to view the full version.
View Full DocumentSorting and Searching  2
%bubble.m
%does a bubble sort of the data vector A
%adapted from E77 reader
%0701 D#
function [A] = bubble(A)
lengthA=length(A);
for n = lengthA1 : 1 : 1
for pointe
r=1:n
This is the end of the preview. Sign up
to
access the rest of the document.
 Spring '08
 Patzek
 Algorithms, Sort, Bubble Sort, Array, Divide and conquer algorithm

Click to edit the document details