Docsity

Algorithms - Data Structures - Lecture Slides, Slides of Data Structures and Algorithms

Partial preview of the text

Download Algorithms - Data Structures - Lecture Slides and more Slides Data Structures and Algorithms in PDF only on Docsity!

Chapter 10

Sorting

Algorithms

Divides the array into two parts: already sorted, and not yet sorted.

On each pass,

  • finds the smallest of the unsorted elements, and
  • swaps it into its correct place,
  • thereby increasing the number of sorted elements by one.

Straight Selection Sort

values [ 0 ]

[ 1 ]

[ 2 ]
[ 3 ]
[ 4 ]

Selection Sort: Pass One

values [ 0 ]

[ 1 ]

[ 2 ]
[ 3 ]
[ 4 ]

U N S O R T E D

SORTED

Selection Sort: Pass Two

values [ 0 ]

[ 1 ]

[ 2 ]
[ 3 ]
[ 4 ]
U N S O R T E D

Selection Sort: End Pass Two

values [ 0 ]

[ 1 ]

[ 2 ]
[ 3 ]
[ 4 ]

U N S O R T E D

SORTED

Selection Sort: End Pass Three

values [ 0 ]

[ 1 ]

[ 2 ]
[ 3 ]
[ 4 ]
S O R T E D
UNSORTED

Selection Sort: Pass Four

values [ 0 ]

[ 1 ]

[ 2 ]
[ 3 ]
[ 4 ]
S O R T E D
UNSORTED

Selection Sort:

How many comparisons?

values [ 0 ]

[ 1 ]

[ 2 ]
[ 3 ]
[ 4 ]

4 compares for values[0]

3 compares for values[1]

2 compares for values[2]

1 compare for values[3]

= 4 + 3 + 2 + 1

For selection sort in general

  • The number of comparisons when the

array contains N elements is

Sum = (N-1) + (N-2) +... + 2 + 1

Arithmetic series:

O(N 2 )

N

N N

i

Sum i

template int MinIndex(ItemType values [ ], int start, int end) // Post: Function value = index of the smallest value // in values [start].. values [end]. { int indexOfMin = start ;

for(int index = start + 1 ; index <= end ; index++) if (values[ index] < values [indexOfMin]) indexOfMin = index ;

return indexOfMin;

}

template void SelectionSort (ItemType values[ ], int numValues )

// Post: Sorts array values[0.. numValues-1 ] // into ascending order by key { int endIndex = numValues - 1; for (int current=0; current<endIndex; current++)

Swap (values[current], values[MinIndex(values, current, endIndex)]);

}

Compares neighboring pairs of array elements,

  • starting with the last array element, 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

values [ 0 ]

[ 1 ]

[ 2 ]
[ 3 ]
[ 4 ]

Snapshot of BubbleSort