21 Sorting and Searching

21 Sorting and Searching - 21 - Sorting and Searching Being...

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon
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(n-1) . Continuing this way, the pointer sorts the array. Here is the code to do a bubble sort:
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Sorting and Searching - 2 %bubble.m %does a bubble sort of the data vector A %adapted from E77 reader %07-01 D# function [A] = bubble(A) lengthA=length(A); for n = lengthA-1 : -1 : 1 for pointe r=1:n
Background image of page 2
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

Page1 / 5

21 Sorting and Searching - 21 - Sorting and Searching Being...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online