Sorting – Part I CS 367 – Introduction to Data Structures
Searching We have already seen many methods to search for data –brute force –binary search –hashing –sorted binary trees Most searching algorithms rely on data to be in some order –especially for arrays
Sorting Arrays It is common to insert data into an array out of order –imagine reading a line of text from a file –inserting students grades To make searching of this data more efficient, it needs to be sorted –if you are to do a lot of searching, the expense to do a sort is easily paid back
Insertion Sort Basic procedure –start at array element 1 –if an element is smaller than any of the elements proceeding it, shift all the elements larger than element to the right by 1 –insert the element into blank space
Insertion Sort cbefdga bcefdga bcdefga abcdefg insert b at position 0 insert d at position 2 insert a at postion 0
Insertion Sort Code public void insertionSort(Object[ ] data) { Comparable tmp; int i, k; for(i = 1; i < data.length; i++) { tmp = Object[i]; for(k = i; (k>0) && tmp.compareTo(data[k-1]) < 0; k--) data[k] = data[k-1]; data[i] = tmp; }
Selection Sort Basic procedure –find the smallest element in the array swap it with the element at index 0 –find the next smallest element swap it with the element at index 1 –continue this until all the elements are in the right spot
Selection Sort cbefdga abefdgc abcfdge abcdfge swap a with c swap c with e swap d with f swap e with f abcdegf abcdefg swap f with g
Selection Sort Code public void selectionSort(Object[ ] data) { int i, k, least; for(i=0; i<data.length-1; i++) { least = i; for(k = i+1; k<data.length; k++) { if(((Comparable)data[k]).compareTo(data[least]) < 0) least = k; } swap(i, least); }
Bubble Sort Basic procedure –start at the back of an array –compare last element with second to last swap them if last element is smaller –compare second to last with third to last swap them if second to last is smaller –repeat The idea is that on each pass, the smallest element will “bubble” to the top
Bubble Sort cbeagfd cbeagdf cbeadgf cbeadgf swap d with f swap d with g no swap swap a with e cbaedgf cabedgf swap a with b acbedgf swap a with c repeat
Bubble Sort Code public void bubbleSort(Object[ ] data) { int i, k; for(i = 0; i<data.length – 1; i++) { for(k = data.length – 1; k > i; k- - ) if(((Comparable)data[k]).compareTo(data[k-1]) < 0) swap(k, k-1); }
Sorting So Far Advantages –all of the sorting methods discussed so far are fairly simple to implement Disadvantage –all of them operate at O(n 2 ) efficiency –insertion and bubble sort specifics lots of wasted copying may move an item and then move it back