{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

20-Sorting

# 20-Sorting - Selection Sort We are sorting an array of N...

This preview shows pages 1–5. Sign up to view the full content.

We are sorting an array of N elements. Algorithm 1) Set currentIndex = 0 2) For each sub-array that starts from currentIndex and goes until the end of the array ( N-1 ): - Find the smallest element - Swap the smallest element with the one at currentIndex Example: 1 st sub-array: [ 35 , 65, 30, 60, 20 ] [ 20 , 65, 30, 60, 35 ] 2 nd sub-array: 20 , [ 65 , 30 , 60, 35 ] 20 , [ 30 , 65 , 60, 35 ] 3 rd sub-array: 20 , 30 , [ 65 , 60, 35 ] 20 , 30 , [ 35 , 60, 65 ] Selection Sort Selection Sort

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
Algorithm 1) Do: 2) Set sorted = true 3) For each pair of adjacent array elements: - If the pair is out of order then swap the elements and set sorted = false 4) While the array is not sorted Example: 1 st pair: [ 35, 65 , 30, 60, 20] [ 35, 65 , 30, 60, 20] 2 nd pair:[35, 65, 30 , 60, 20] [35, 30, 65 , 60, 20] 3 rd pair: [35, 30, 65, 60 , 20] [35, 30, 60, 65 , 20] Bubble Sort Bubble Sort
Pairs do not have to be adjacent. for ( int i = 0; i < N - 1; i++ ) for ( int j = i + 1; j < N; j++ ) if ( array[j] <array[i] ) swap(array[j], array[i]); Bubble Sort 2.0 Bubble Sort 2.0

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
Algorithm 1) When we start the first element is our sorted sub- array 2) For each element in unsorted portion of the array: - Insert it at the appropriate position into
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}

### Page1 / 12

20-Sorting - Selection Sort We are sorting an array of N...

This preview shows document pages 1 - 5. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online