Docsity

Data Structures and Algorithm Analysis: A Comprehensive Guide to Sorting Algorithms, Slides of Data Structures and Algorithms

Partial preview of the text

Download Data Structures and Algorithm Analysis: A Comprehensive Guide to Sorting Algorithms and more Slides Data Structures and Algorithms in PDF only on Docsity!

Data Structures &

Algorithm Analysis

Sorting

• Given a set (container) of n elements

– E.g. array, set of words, etc.

• Suppose there is an order relation that can be

set across the elements

• Goal Arrange the elements in ascending order

– Start  1 23 2 56 9 8 10 100

– End  1 2 8 9 10 23 56 100

Bubble Sort

---- finish the first traversal ----

---- start again ----

1 1 2 23 9 8 10 56 100

2 1 2 9 23 8 10 56 100

3 1 2 9 8 23 10 56 100

4 1 2 9 8 10 23 56 100

---- finish the second traversal ----

---- start again ----

………………….

Why Bubble Sort?

Implement Bubble Sort

with an Array

void bubbleSort (Array S, length n) {

boolean isSorted = false; while(!isSorted) { isSorted = true; for(i = 0; i<n; i++) { if(S[i] > S[i+1]) { int aux = S[i]; S[i] = S[i+1]; S[i+1] = aux; isSorted = false; } }

}

Sorting Algorithms Using Priority

Queues

  • Remember Priority Queues = queue where the dequeue operation always

removes the element with the smallest key  removeMin

  • Selection Sort
    • insert elements in a priority queue implemented with an unsorted sequence
    • remove them one by one to create the sorted sequence
  • Insertion Sort
    • insert elements in a priority queue implemented with a sorted sequence
    • remove them one by one to create the sorted sequence

Selection Sort

  • insertion: O(1 + 1 + … + 1) = O(n)
  • selection: O(n + (n-1) + (n-2) + … + 1) = O(n 2 )

Sorting with Binary Trees

• Using heaps (see lecture on heaps)

– How to sort using a minHeap?

• Using binary search trees (see lecture on BST)

– How to sort using BST?

Heap Sorting

• Step 1: Build a heap

• Step 2: removeMin( )

Recall: Heap Removal

• Remove element

from priority queues?

removeMin( )

Recall: Heap Removal

• Begin downheap

Next

• Sorting algorithms that rely on the “DIVIDE

AND CONQUER” paradigm

– One of the most widely used paradigms

– Divide a problem into smaller sub problems, solve

the sub problems, and combine the solutions

– Learned from real life ways of solving problems

Divide-and-Conquer

  • Divide and Conquer is a method of algorithm design that

has created such efficient algorithms as Merge Sort.

  • In terms or algorithms, this method has three distinct

steps:

  • Divide : If the input size is too large to deal with in a straightforward manner, divide the data into two or

more disjoint subsets.

  • Recur : Use divide and conquer to solve the subproblems associated with the data subsets.
  • Conquer : Take the solutions to the subproblems and “merge” these solutions into a solution for the original problem.

Merge-Sort

Merge-Sort(cont.)