Docsity

Sorting Algorithms, Exams of Advanced Algorithms

Partial preview of the text

Download Sorting Algorithms and more Exams Advanced Algorithms in PDF only on Docsity!

Sorting Algorithms

  • (^) Slide 2-3 – Insertion Sort
  • (^) Slides 4-44 – Merge Sort along with illustrative example
  • (^) Slides 46-48 – Quick Sort along with illustrative example
  • (^) Slides 49-64 – Counting sort along with illustrative example

Insertion Sort

for(int i=1; i<=length-1; i++) int j=i; while(j>0 and A(j-1) > A(j) ) swap A(j-1) and A(j) j=j- end while end for On your left, is the pseudo code for insertion sort. Below is an example of how this sorting technique works with actual array elements. Sorting is typically done in- place, by iterating up the array, growing the sorted list behind it.

Merge Sort

A divide-and-conquer algorithm :

  • (^) Divide the unsorted array into 2 halves until the sub-arrays only contain one element
  • (^) Merge the sub-problem solutions together:
    • (^) Compare the sub-array’s first elements
    • (^) Remove the smallest element and put it into the result array
    • (^) Continue the process until all elements have been put into the result array

Merge Sort continued

Mergesort(Pass an array) if array size > 1 Divide array in half Call Mergesort on first half. Call Mergesort on second half. Merge two halves. Merge(Pass two arrays) Compare leading element in each array Select lower and place in new array. (If one input array is empty then place remainder of other array in output array) MergeSort(A, left, right) { if (left < right) { mid = floor((left + right) / 2); MergeSort(A, left, mid); MergeSort(A, mid+1, right); Merge(A, left, mid, right); } } // Merge() takes two sorted subarrays of A and // merges them into a single sorted subarray of A // (how long should this take?)

Merge

Merge

Merge

Merge

Merge

Merge

Merge