Data Structures Chapter 4 Basic Sorting Algorithms 1

Data Structures Chapter 4: Basic Sorting Algorithms 1

Out Line Introduction Bubble Sort Algorithm Selection Sort Algorithm Insertion Sort Algorithm 2

Introduction The two most common operations performed on data stored in a computer are storing and searching. This chapter introduces you to the fundamental algorithms for sorting and searching data. These algorithms depend on only the array as a data structure. 3

Sorting Algorithms Most of the data we work with in our day to day lives is sorted. Sorting is a fundamental process in working with data and deserves close study. Example: We look up a phone number by moving through the last names in the book alphabetically. 4

Bubble Sort Algorithms The bubble sort is one of the slowest sorting algorithms available, but it is also one of the simplest sorts to understand implement, which makes it an excellent candidate for our first sorting algorithm. The sort gets its name because ''float like a bubble'' from one end of the list to another. 5

Bubble Sort Algorithms 6

Exercise (Bubble Sort Example) 7

Bubble Sort Algorithms for (int pass= 1, pass<length, pass++) for (int i= 0; i<length-1; i++) if (b[i] > b[i+1]) swap(b[i], b[i+1]); The outer loop uses to repeat the process of comparison. The inner loop compares the two adjacent positions indicated by I and i+1, swapping them if necessary. 8

Selection Sort Algorithms This sort works by starting at the beginning of the array, comparing the first element with the other elements in the array. The smallest element is placed in position 0, and the sort then begins at position 1. This continues until each position except the last position has been the starting point for a new loop. 9

Selection Sort Algorithms 10

Insertion Sort Algorithms The insertion sort is an analog to the way we normally sort things numerically or alphabetically. The insertion sort works not by making exchanges, but by moving larger array elements to the right to make room for smaller elements on the left side of the array. 11

Insertion Sort Algorithms 12

Insertion Sort Algorithms 13

The end. Questions 14
- Slides: 14