Sorting algorithms. Bubble sort and Insertion sort

11.5.2.4 write an algorithm /pseudo-code for sorting by insertion and bubble sort  

Sorting algorithms

Sorting is putting items of data into a precise order, for example alphabetical or numerical.

Compare - assess how items of data are similar of different to each other, to help decide which order they should go in.

When we sorting data items it is essential to compare them woth 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 - anoother 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.

Pseudocode

N = Array.Size

for = 0 to N-2    // passes

for = 0 to N-i-1    // 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

Pseudocode

N = Array.Size

for = 1 to N - 1    // if the fisrt index of array 0

j  

while arr[i] arr[i-1]      

buf = arr[i]    // swapping  

arr[i] = arr[i-1]       

arr[i-1] = buf     

if > 2

then - 1 // turn element comparisons to the left

endif

endwhile

endfor

 

Additionally Visualisation


Questions:

  1. Name two sorting algorithms.
  2. Explain how working each sorting algorithm.

Exercises:

Ex. 1 "Bubble sort"

Ex. 2 "Insertion sort"

Ex. 3 "Bubble sort - 2"

Ex. 4 "Insertion sort - 2"

Ex. 5 Write down 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 program to implement Insertion sort.

 

1) Fill array 20 random numbers [0, 100]

2) Output array

3) Sort array

4) Output array


Exam questions:

Категория: Programming languages | Добавил: bzfar77 (11.02.2021)
Просмотров: 119 | Теги: array, Insertion sort, algorithm, Sort, Bubble sort, Compare elements, Pass | Рейтинг: 5.0/1
Всего комментариев: 0
avatar