Sorting Sorting places data in ascending or descending order, based on one or more sort keys E.g. A list of names could be sorted alphabetically, bank.

Similar presentations

Presentation on theme: "Sorting Sorting places data in ascending or descending order, based on one or more sort keys E.g. A list of names could be sorted alphabetically, bank."— Presentation transcript:

2SortingSorting places data in ascending or descending order, based on one or more sort keysE.g.A list of names could be sorted alphabetically,bank accounts could be sorted by account number,employee payroll records could be sorted by social security numberHow do you sort a list/array of data?A sorting algorithm is said to be in-place if it requires very little additional space besides the initial array holding the elements that are to be sorted. Normally “very little” is taken to mean that for sorting nnn elements, O⁢(log⁡n)OnO(\log n) extra space is required

3Popular sorting algorithms:Selection sortInsertion sortMerge sortBubble sortQuick sortThe end result (sorted array) is the same no matter which algorithm you use to sort the array.The choice of algorithm affects only the run time and memory use of the program.Non-Comparison Based Sorting AlgorithmsIn the previous lessons we discussed three basic sorting algorithms, bubble sort, insertion sort and selection sort, each of which is easy to implement, but takes O(n2) steps in average case to sort a list of size n. More advanced recursive algorithms like Quick Sort and Merge Sort are hard to implement, but runs more efficiently on a set of data, typically in O(n log n) steps. All five algorithms assume comparison of the whole key to make the decision to sort. There are simpler algorithms that can sort a list using partial information about the keys. There are two algorithms we discussed in this section called Bucket Sort and radix Sort.Bucket SortThe idea of the bucket sort is to place items into various buckets based on a key or partial information about a key. For example, if we have a list that contains only numbers from 0.. 99, then we can take 10 buckets and place all elements that are between 0..9 into first bucket, into second bucket etc. This is a kind of sorting that only requires O(n) steps. A more general sorting algorithm is the radix sort that works as follows.Radix SortSuppose we are able to compare parts of the data to make a decision. Say we have a bunch of numbers we need to sort. Assume we have the following numbers.12, 67, 45, 42, 18, 60Assume we have 10 buckets we can work with. First we place each item in the bucket based on the least significant digit (that is 1 place). So we have the numbers in buckets as follows. 4260 12 45 67 18 0 1 2 3 4 5 6 7 8 9Next we sort the numbers again by second digit (that is 10 place) and place them in buckets. In the process we need to make sure that we are not changing the order of the elements. 18 45 67 12 42 60 Now note that if we just collect the numbers from left to right, and bottom to top in each bucket, we have a sorted list of numbers. This is called the Radix Sort and complexity of the Radix Sort is O(nb) where b is the number of digits in the largest number.Note radix sort can be applied to data that can be compared partially like integers of characters. However, Radix sort cannot be applied to data that needs to be compared as a whole (eg: nodes)

4Selection Sort Simple sorting algorithm First iteration:selects the smallest element in the array and swaps it with the first element.Second iteration:selects the second-smallest item and swaps it with the second element.After the ith iteration:the smallest i items of the array will be sorted into increasing order in the first i elements of the array.Selection sort sorts an array by repeatedly finding the smallest element of the unsorted tail region and moving it to the front.Example: sorting an array of integers

5Sorting an Array of IntegersFind the smallest and swap it with the first elementFind the next smallest. It is already in the correct placeFind the next smallest and swap it with first element of unsorted portionRepeatWhen the unsorted portion is of length 1, we are done

11Analyzing the Performance of the Selection Sort AlgorithmThe number of visits:n (n - 1) (n - 2)This can be simplified to n2 /2 + 5n/2 - 35n/2 - 3 is small compared to n2 /2 – so let's ignore itAlso ignore the 1/2 – it cancels out when comparing ratios

12Analyzing the Performance of the Selection Sort AlgorithmThe number of visits is of the order n2 .Computer scientists use the big-Oh notation to describe the growth rate of a function.Using big-Oh notation: The number of visits is O(n2).To convert to big-Oh notation: locate fastest-growing term, and ignore constant coefficient.

16Insertion SortLike selection sort, maintains a sorted portion(left) and a unsorted portion (right)in arrayFist iteration starts with second element in array and insert it into correct position in sorted portion in arrayThe second iteration looks at the third element and inserts it into the correct position with respect to the first two, so all three elements are in order.and so on….

22Insertion SortInsertion sort is the method that many people use to sort playing cards. Pick up one card at a time and insert it so that the cards stay sorted.Insertion sort is an O(n2) algorithm.for (int i = 1; i < a.length; i++){int temp = a[i];int j;for(j = i-1;j>=0 && temp<a[j] ;j--)a[j+1]= a[j];}a[j+1] = temp;

23Merge Sort Sorts an array byCutting the array in halfRecursively sorting each halfMerging the sorted halvesDramatically faster than the selection sort In merge sort, one sorts each half, then merges the sorted halves.

24Merge Sort Example Divide an array in half and sort each halfMerge the two sorted arrays into a single sorted array

25Programming QuestionImplement MergeSorter.java. You can write your sorting code in sort method that accepts an int array and call it from main.Note that the base case is an array with only one element and it simply return the same array as sorted array.Steps:Break array into halves/two sub arrays first, secondSort first halfSort second halfMerge first and second halfImplement a method merge for this. Method should accept 3 parameters (first, second, and array into which you want to merge first and second):public static void sort(int[] a)private static void merge(int[] first, int[] second, int[] a)

34Searching Linear search: also called sequential searchExamines all values in an array until it finds a match or reaches the endNumber of visits for a linear search of an array of n elements:The average search visits n/2 elementsThe maximum visits is nA linear search locates a value in an array in O(n) steps

35Programming QuestionImplement the class LinearSearch. Implement the method search that performs linear search. The method should accept as parameters an int array and search value. The method should return the index of the value if found in array or -1 otherwise.Then implement the tester class LinearSearchDemo that test sort method of LinearSearch class.A sample output is shown:Program Run:[46, 99, 45, 57, 64, 95, 81, 69, 11, 97, 6, 85, 61, 88, 29, 65, 83, 88, 45, 88]Enter number to search for, -1 to quit: 12Found in position -1Enter number to search for, -1 to quit: -1

38QuestionIf your array is sorted can you do a faster search than linear search?

39Binary Search A binary search locates a value in a sorted array by:Get middle element in arrayIf middle==searhckey return successElseDivide array into two halves.Determining whether the value occurs in the first or second halfThen repeating the search in one of the halvesThe size of the search is cut in half with each step.Animator:

40Binary Search Searching for 15 in this arrayThe last value in the first half is 9So look in the second (darker colored) halfThe last value of the first half of this sequence is 17Look in the darker colored sequence

41Binary SearchThe last value of the first half of this very short sequence is 12 (<15),This is smaller than the value that we are searching,so we must look in the second half15 ≠ 17: we don't have a match

51Comparing ObjectsArrays.sort sorts objects of classes that implement Comparable interface:public interface Comparable{int compareTo(Object otherObject);}The call a.compareTo(b) returnsA negative number if a should come before b0 if a and b are the sameA positive number otherwise