Docsity

Sorting Algorithms: An Overview of Insertion Sort and Its Implementation, Slides of Computer Science

Partial preview of the text

Download Sorting Algorithms: An Overview of Insertion Sort and Its Implementation and more Slides Computer Science in PDF only on Docsity!

Sorting

  • Rearrange a[0], a[1], …, a[n-1] into ascending order. When done, a[0] <= a[1] <= … <= a[n-1]
  • 8, 6, 9, 4, 3 => 3, 4, 6, 8, 9

Sort Methods

  • Insertion Sort
  • Bubble Sort
  • Selection Sort
  • Count Sort
  • Shaker Sort
  • Shell Sort
  • Heap Sort
  • Merge Sort
  • Quick Sort

Insert an Element

  • 3, 6, 9, 14 insert 5
  • Compare new element (5) and last one (14)
  • Shift 14 right to get 3, 6, 9, , 14
  • Shift 9 right to get 3, 6, , 9, 14
  • Shift 6 right to get 3, , 6, 9, 14
  • Insert 5 to get 3, 5, 6, 9, 14

Insert An Element

// insert t into a[0:i-1]

int j;

for (j = i - 1; j >= 0 && t < a[j]; j--)

a[j + 1] = a[j];

a[j + 1] = t;

Insertion Sort

  • • Sort 7, 3, 5, 6,
  • • Start with 7 and insert 3 => 3,
  • • Insert 5 => 3, 5,
  • • Insert 6 => 3, 5, 6,
  • • Insert 1 => 1, 3, 5, 6,

Insertion Sort

for (int i = 1; i < a.length; i++)

{// insert a[i] into a[0:i-1]

// code to insert comes here

}