Transcript Exchange Sort (bubble Sort)
Zabin Visram Room CS115 Lecture Structure
References
Exchange Sort (bubble Sort)
CS126 ZV 2005 Exchange Sort(Bubble Sort)
1
Exchange sort
Basic operation of Exchange sort is the exchange of adjacent pair of elements Overall sort consist of a number of passes over the data Each pass starts at one end of the array and works toward the other end Each pair of elements that are out of order are exchanged CS126 ZV 2005 Exchange Sort(Bubble Sort)
2
Exchange Sort
390 250 182 45 235 250 390 182 45 235 250 182 390 45 235 250 182 45 390 235 250 182 45 235
390 (a) (b) (c ) (d) (e)
The first pass of an exchange sort CS126 ZV 2005 Exchange Sort(Bubble Sort) (a) In first pass 390 is compared with 205; then exchanged as 250 is smaller (b) 390 is compared with 182, they exchanged. Result shown in (c ) In (c )390 is compared with 45, they exchanged Then in (d) 390 is compared with 235 and exchanged Result is (e) – regarding the columns as arrays - element 390 has ‘bubbled’ from index 0 to highest index (4)
3
bubbling
The elements with largest value are moving slowly or
bubbling
to the top If no exchanges are made during one pass over the data, the data have been sorted and process terminates CS126 ZV 2005 Exchange Sort(Bubble Sort)
4
Analysis
The first pass moves the largest element to the
n
th, forming a sorted list of one.
The second pass has to consider only
n
-1 elements The second pass moves the second largest element to the n-1 position. Therefore the third pass only needs to consider
n
-2 elements and so on CS126 ZV 2005 Exchange Sort(Bubble Sort)
5
public static void bubbleSort(int data[], int n) { //pre: 0 <= n <= data.length
//post: values in data[0..n-1] are in //ascending order int numSorted = 0; //number of values //in order while (numSorted < n) { //bubble a large element to correct //position for (int index = 1; index
CS126 ZV 2005 Exchange Sort(Bubble Sort)
6
public static void bubbleSort(int data[], int n) { //pre: 0 <= n <= data.length
//post: values in data[0..n-1] are in //ascending order int numSorted = 0; //number of values //in order while (numSorted < n) { //bubble a large element to correct //position for (int index = 1; index
//post: data[i] and data[j] are exchanged int temp; temp = data[i]; 7
Disadvantages
Two disadvantages of this sort are: (i) the use of swap (requiring three assignments) within the inner loop; (ii) the fact that moves are never by more than one position at a time. (Compare selection sort which has no moves in the inner loop and elements may move large distances.) CS126 ZV 2005 Exchange Sort(Bubble Sort)
8
Demonstration of Bubble Sort
http://www.cosc.canterbury.ac.nz/people/m ukundan/dsal/BSort.html
CS126 ZV 2005 Exchange Sort(Bubble Sort)
9