Docsity

Lecture 12: Elementary Sorting with Data Structures & Algorithms, Slides of Data Structures and Algorithms

Partial preview of the text

Download Lecture 12: Elementary Sorting with Data Structures & Algorithms and more Slides Data Structures and Algorithms in PDF only on Docsity!

Data Structures and Algorithms

LECTURE 12 – ELEMENTARY SORTING

Sorting

  • Rearranging the elements in a data structure, either ascending order, or descending

order

  • Elementary Sorting
    • Bubble Sort
    • Selection Sort
    • Insertion Sort

Bubble Sort

  • Compares neighboring pairs of array elements, and swaps

neighbors whenever they are not in correct order

  • On each pass, this causes the smallest element to “bubble up”

to its correct place in the array

Bubble Sort

Bubble Sort void bubbleSort( int arr[], int size) { int temp = 0; for ( int i=0; i < size; i++) { for ( int j = size-1; j>i; j--) { if (arr[j] < arr[j-1] ) { temp = arr[j]; arr[j] = arr[j-1]; arr[j-1] = temp; } } } }

Bubble Sort

  • 6 compares for element at [0] = N- 1
  • 5 compares for element at [1] = N- 2
  • 4 compares for element at [2]
  • 3 compares for element at [3]
  • 2 compares for element at [4] = 2
  • 1 compares for element at [5] = 1
  • 0 compares for element at [6] = 0

SELECTION SORT

Selection Sort

  • On each pass, finds the smallest of the unsorted elements, and

swaps it into its correct place

  • The algorithm works as:
    • Find the element with a minimum value in the list
    • Swap it with the element in the first position
    • Repeat it for remaining elements; however now swap them with the elements starting at the second position and advancing each time

Complexity of Selection Sort

  • Total comparisons:
  • N-1 + N-2 + ... + 3 + 2 + 1 + 0 = N(N−1)/
  • Which is O(N 2
  • Although the number of comparisons are same as bubble sort,

however, number of swaps are decreased

  • Total No. of swaps in Selection sort are: (N - 1)

Selection Sort void selectionSort( int arr[], int size) { for ( int i=0; i < size; i++) { int min = i; for ( int j=i+1; j < size; j++) if (arr[j] < arr[min]) min = j; if (min != i) { int temp = arr[i]; arr[i] = arr[min]; arr[min] = temp; } } }

Insertion Sort

  • The algorithm gradually builds a sorted array by selecting an

element from an unsorted array, and placing it in its right position

  • The rest of the elements are shifted to make room for this

placement

Insertion Sort

Insertion Sort void insertionSort( int arr[], int size) { for ( int i=1; i < size; i++) { int value = arr[i]; for ( int j = i-1; j >= 0 && arr[j] > value; j--) arr[j+1] = arr[j]; arr[j+1] = value; } }