Sorting Algorithms
Sorting Algorithms
sorting
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.
Example:
Another Example: 12, 11, 13, 5, 6
Let us loop for i = 1 (second element of the array) to 4 (last element of the
array)
i = 1.
Since 11 is smaller than 12, move 12 and insert 11 before 12
11, 12, 13, 5, 6
i = 2.
13 will remain at its position as all elements in A[0..I-1] are smaller than 13
11, 12, 13, 5, 6
i = 3.
5 will move to the beginning and all other elements from 11 to 13 will move
one position ahead of their current position.
5, 11, 12, 13, 6
i = 4.
6 will move to position after 5, and elements from 11 to 13 will move one
position ahead of their current position.
5, 6, 11, 12, 13
Logic
for(i=1;i<count;i++)
{
temp=number[i];
j=i-1;
while((temp<number[j])&&(j>=0))
{
number[j+1]=number[j];
j=j-1; }
number[j+1]=temp;
}
MERGE SORT
Merge Sort Approach
• To sort an array A[p . . r]:
• Divide
– Divide the n-element sequence to be sorted into
two subsequences of n/2 elements each
• Conquer
– Sort the subsequences recursively using merge sort
– When the size of the sequences is 1 there is
nothing more to do
• Combine
– Merge the two sorted subsequences
13
Merge Sort
p q r
1 2 3 4 5 6 7 8
Alg.: MERGE-SORT(A, p, r) 5 2 4 7 1 3 2 6
14
Example – n Power of 2
1 2 3 4 5 6 7 8
Divide 5 2 4 7 1 3 2 6 q=4
1 2 3 4 5 6 7 8
5 2 4 7 1 3 2 6
1 2 3 4 5 6 7 8
5 2 4 7 1 3 2 6
1 2 3 4 5 6 7 8
5 2 4 7 1 3 2 6
15
logic
1. MERGE_SORT(arr, beg, end)
2.
17
Quicksort A[p…q] A[q+1…r]
≤
• Conquer
– Recursively sort A[p..q] and A[q+1..r] using Quicksort
• Combine
– Trivial: the arrays are sorted in place
– No additional work is required to combine them
– The entire array is now sorted
18
QUICKSORT
Initially: p=1, r=n
Alg.: QUICKSORT(A, p, r)
if p < r
then q ← PARTITION(A, p, r)
QUICKSORT (A, p, q)
5 3 2 6 4 1 3 7 5 3 2 6 4 1 3 7
i j i j
3 3 2 6 4 1 5 7 3 3 2 6 4 1 5 7
i j i j
A[p…q] A[q+1…r]
3 3 2 1 4 6 5 7 3 3 2 1 4 6 5 7
i j j i
21
Example
22
Partitioning the Array
Alg. PARTITION (A, p, r)
r
1. x ← A[p]
p
A: 5 3 2 6 4 1 3 7
2. i ← p – 1
3. j ← r + 1 i j
4. while TRUE A[p…q] ≤ A[q+1…r]
5. do repeat j ← j – 1
A: ap ar
6. until A[j] ≤ x
7. do repeat i ← i + 1 j=q i
8. until A[i] ≥ x
9. if i < j Each element is
visited once!
10. then exchange A[i] ↔ A[j]
Running time: Θ(n)
11. else return j n=r–p+1
23
Time complexity of sortings