Elementary Sorting Techniques
Elementary Sorting Techniques
CASET College
Bubble sort starts with very first two elements, comparing them to check
which one is greater.
Next we compare 33 and 35. We find that both are in already sorted
positions.
We know then that 10 is smaller 35. Hence they are not sorted.
We swap these values. We find that we have reached the end of the
array. After one iteration, the array should look like this −
To be precise, we are now showing how an array should look like after
each iteration. After the second iteration, it should look like this −
Notice that after each iteration, at least one value moves at the end.
And when there's no swap required, bubble sorts learns that an array is
completely sorted.
Hina Gojwari
CASET College
Algorithm
We assume list is an array of n elements. We further assume
that swap function swaps the values of the given array elements.
begin BubbleSort(list)
return list
end BubbleSort
Complexity
place and then it has to be inserted there. Hence the name insertion
sort.
This algorithm is not suitable for large data sets as its average and
worst case complexity are of Ο (n2).
Algorithm
To sort an array of size n in ascending order:
1: Iterate from arr[1] to arr[n] over the array.
2: Compare the current element (key) to its predecessor.
3: If the key element is smaller than its predecessor, compare it to
the elements before. Move the greater elements one position up to
make space for the swapped element.
Hina Gojwari
CASET College
Example:
Another Example:
Insertion sort is a simple sorting algorithm that works similar to the way
you sort playing cards in your hands. The array is virtually split into a
sorted and an unsorted part. Values from the unsorted part are picked
and placed at the correct position in the sorted part.
Complexity
Merge sort is the algorithm which follows divide and conquer approach.
Consider an array A of n number of elements. The algorithm processes
the elements in 3 steps.
The main idea behind merge sort is that, the short list takes less time to
be sorted.
Complexity
Algorithm
MergeSort(arr[ ], l, r)
If r > l
1. Find the middle point to divide the array into two halves:
middle m = l+ (r-1)/2
The following example shows the complete merge sort process for an
example array {38, 27, 43, 3, 9, 82, 10}. If we take a closer look at the
diagram, we can see that the array is recursively divided into two halves till
the size becomes 1. Once the size becomes 1, the merge processes come
into action and start merging arrays back till the complete array is merged.
Example: