Download Sorting Algorithms: Selection Sort, Insertion Sort, Bubble Sort, Merge Sort and more Study notes Computer Science in PDF only on Docsity!
1
CS162: Introduction to Computer
Science II
Sorting
2
Sorting Algorithms
• A sorting algorithms rearranges the
elements so that they are in ascending or
descending order
• Note: we will discuss sorting algorithms
briefly
• You will see it again and in more depth in
later Computer Science courses
3
Selection Sort
Selection sort works by:
- Finding the smallest element of the unsorted region
- Swapping that smallest element with the first element in the unsorted region
We will shade the sorted region grey and the unsorted region will remain white
4
Selection Sort
7
Complexity of Selection Sort
Complexity of selectionSort:
[i=0] minimumPosition: visits n elements
swap: visits 2 elements
[i=1] minimumPosition: visits n-1 elements
swap: visits 2 elements
[i=2] minimumPosition: visits n-2 elements
swap: visits 2 elements
[i=n-2] minimumPosition: visits 2 elements
swap: visits 2 elements
8
Complexity of Selection Sort
• Adding up the red numbers from the
previous slide:
n^2 n On^2
n
nn
n n n
n n n
n n
L
L
L
Note that 2 ( 1 ) −
nn
L n n
9
Profiling the Selection Sort
Algorithm
10
Insertion Sort
• Assume the initial sequence a[0] a[1] …
a[k] is already sorted
• k = 0 when the algorithm starts
• Insert the array element at a[k+1] into the
proper location of the initial sequence
• Note that the insertion enlarges the initial
sequence
13
Insertion Sort
public void insertSort(int[] a) { for( int i = 1; i < a.length; i++ ){ int next = a[i]; // Find the insertion location // Move all larger elements up int j = i; while( j > 0 && a[j-1] > next) { a[j] = a[j-1]; j--; } // Insert the element a[j] = next; } }
14
Complexity of Insertion Sort
- for loop runs for (n-1) iterations
- On the kth iteration:
- We have k elements that are already sorted
- Need to insert into these k elements and move up the elements that are past the insertion point => k+ elements visited
- Total # of visits is:
1 2
nn L n
15
Complexity of the insertion sort?
Best case
already in order O(n)
Worst case
reversed O(n^2 )
Average case O(n^2 )
16
Bubble Sort
1. Compare adjacent elements. If the first is greater
than the second, swap them.
2. Do this for each pair of adjacent elements,
starting with the first two and ending with the
last two. At this point the last element should be
the greatest.
3. Repeat the steps for all elements except the last
one.
4. Keep repeating for one fewer element each time,
until you have no more pairs to compare.
19
Bubble Sort
Start at i=1 16 8 15 23 4 42
Swap 16 and 8 8 16 15 23 4 42
Swap 16 and 15 8 15 16 23 4 42
Do nothing 8 15 16 23 4 42
Swap 23 and 4 8 15 16 4 23 42
20
Bubble Sort
This part is sorted. But the non-gray part is still not sorted…so we repeat…(the rest is not shown)
21
Bubble Sort
public void bubbleSort(int[] a) { for (int i = (a.length-1); i >= 0; i--) { for (int j = 1; j<=i; j++){ if (a[j-1] > a[j]){ // Swap elements at j-1 and j int temp = a[j-1]; a[j-1] = a[j]; a[j] = temp; } } } }
22
What's the complexity of the
bubble sort?
Best case
already in order O(n^2 )
Worst case
reversed O(n^2 )
Average case O(n^2 )
Note: best case for the version on the previous slide is O(n 2 ). A differentl version of bubblesort (not the one on the previous slide) has O(n) best case
25
The Merge Function
What’s the complexity of the merge with respect to n (the total number of elements)? O(n)
26
MergeSort
• But wait a second…you aren’t given two
already sorted arrays
• This is where the magic of recursion comes
in:
- Keep dividing the array in half (until the
subarray size is 1)
- Note that a subarray of size 1 is sorted
- Merge the sorted halves together
27
MergeSort
public class MergeSorter { private int[] a; public MergeSorter(int[] anArray) { a = anArray; } public void sort() { if( a.length <= 1 ) return; int[] first = new int[a.length / 2]; int[] second = new int[a.length – first.length]; System.arraycopy(a,0,first,0,first.length); System.arraycopy(a,first.length,second,0,second.length); MergeSorter firstSorter = new MergeSorter(first); MergeSorter secondSorter = new MergeSorter(second); firstSorter.sort(); secondSorter.sort(); merge(first, second); }
28
MergeSort
private void merge(int[] first, int[] second) { // Merge both halves into the temp array // Next element to consider in the first array int iFirst = 0; // Next element to consider in the second array int iSecond = 0; // Next open position in a int j = 0; // As long as neither iFirst nor iSecond past the // end, move the smaller element into a while( iFirst < first.length && iSecond < second.length ) { if( first[iFirst] < second[iSecond] ) { a[j] = first[iFirst]; iFirst++; } else { a[j] = second[iSecond]; iSecond++; } j++; } }
31
Complexity of MergeSort
O(n)
O(n)
O(n)
O(log n)
levels
Total complexity: O(n log(n))
32
Complexity of MergeSort
• Best case and worst case complexity are
O(n log(n))
• Trade-offs:
- coding complexity ↔ execution efficiency
33
Complexity of MergeSort
Is O(n log(n))
faster than O(n^2 )?
Yes!
34
Sorting demos
http://www.student.seas.gwu.edu/~idsv/idsv.html
http://cs.smith.edu/~thiebaut/java/sort/demo.html
http://www.cs.ubc.ca/spider/harrison/Java/sorting-demo.html
http://www.cs.bell-labs.com/cm/cs/pearls/sortanim.html