11.5.2.4 write an algorithm /pseudo-code for sorting by insertion and bubble sort Sorting algorithms
Compare - assess how data items are similar or different to each other, to help decide which order they should go in. When we sort data items it is essential to compare them with each other so that they can be put into the correct order. There may be millions of items of data to compare, so sorting algorithms must carry out the task as efficiently as possible so as not to cause a bottleneck. Another part of the program may not be able to run until the sorting has been carried out. Bubble sort Using a bubble sort. Arrange these numbers in ascending order. Show each step including steps with no change.
PseudocodeN = Array.Size for i = 0 to N-2 // passes for j = 0 to N-i-2 // comparisons in pass if arr[j] > arr[j+1] // comparison of two adjacent elements then buf = arr[j] // swapping arr[j] = arr[j+1] arr[j+1] = buf endif endfor j endfor i Insertion sort
PseudocodeN = Array.Size for j = 1 to N - 1 // if the fisrt index of array 0 i = j while arr[i] < arr[i-1] buf = arr[i] // swapping arr[i] = arr[i-1] arr[i-1] = buf if i > 1 then i = i - 1 // turn element comparisons to the left endif endwhile endfor
Additionally Visualisation Questions:
Exercises: Ex. 1 "Bubble sort"
Ex. 2 "Insertion sort" Ex. 3 "Bubble sort - 2" Ex. 4 "Insertion sort - 2" Ex. 5 Write down the program to implement Bubble sort. 1) Fill array 20 random numbers [0, 100] 2) Output array 3) Sort array 4) Output array Ex. 6 Write down the program to implement Insertion sort. 1) Fill array 20 random numbers [0, 100] 2) Output array 3) Sort array 4) Output array Ex. 7 Bubble sort vs Insertion sort. (Author: Litvinova Olga - CS teacher of NIS Pavlodar) Exam questions: | |
| |
Просмотров: 6654 | | |
Всего комментариев: 0 | |